import { query } from "../_generated/server";
import { v } from "convex/values";

/**
 * Get WhatsApp config for a user (by Prisma ID or email)
 * Used by /api/integrations/whatsapp/status and connect/disconnect routes.
 */
export const getWhatsappConfig = query({
  args: {
    email: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    if (!args.email) return null;
    const email = args.email;

    const user = await ctx.db
      .query("users")
      .withIndex("by_email", (q) => q.eq("email", email))
      .unique();

    if (!user) return null;
    return {
      _id: user._id,
      whatsappConnected: user.whatsappConnected,
      whatsappNumber: user.whatsappNumber ?? null,
      whatsappConnectedAt: user.whatsappConnectedAt ?? null,
      n8nWebhookUrl: user.n8nWebhookUrl ?? null,
      n8nWorkflowId: user.n8nWorkflowId ?? null,
    };
  },
});

/**
 * Get knowledge base FAQ entries for an organization (keyword search).
 * Mirrors the Prisma company_knowledge_base.findMany used in queryKnowledgeBase().
 */
export const getKnowledgeBaseEntries = query({
  args: {
    organizationId: v.string(),
    language: v.optional(v.string()),
    limit: v.optional(v.number()),
    // Accepted for Prisma-adapter compatibility — already enforced internally.
    isActive: v.optional(v.boolean()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    let q = ctx.db
      .query("company_knowledge_base")
      .withIndex("by_organizationId", (q) =>
        q.eq("organizationId", args.organizationId),
      )
      .filter((f) => f.eq(f.field("isActive"), true));
    if (args.language) {
      q = q.filter((f) => f.eq(f.field("language"), args.language as string));
    }
    const entries = await q.order("desc").take(limit);

    return entries.map((e) => ({
      id: e._id,
      prismaId: e.prismaId ?? null,
      organizationId: e.organizationId,
      question: e.question,
      answer: e.answer,
      category: e.category ?? null,
      language: e.language,
      priority: e.priority,
      isActive: e.isActive,
    }));
  },
});

/**
 * Get WhatsApp conversations for a user
 * Phase 6: WhatsApp & Voice Agents
 */
export const getConversations = query({
  args: {
    userId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;
    return await ctx.db
      .query("whatsapp_conversations")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get messages for a WhatsApp conversation
 * Phase 6: WhatsApp & Voice Agents
 */
export const getMessages = query({
  args: {
    conversationId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 100;
    return await ctx.db
      .query("conversation_messages")
      .withIndex("by_conversationId", (q) =>
        q.eq("conversationId", args.conversationId),
      )
      .order("asc")
      .take(limit);
  },
});

/**
 * Get multi-tenant org WhatsApp conversations
 * Phase 6: WhatsApp & Voice Agents
 */
export const getOrgConversations = query({
  args: {
    organizationId: v.string(),
    userPhone: v.optional(v.string()),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 50;

    // If userPhone is specified, use the compound index for direct lookup
    if (args.userPhone) {
      return await ctx.db
        .query("org_whatsapp_conversations")
        .withIndex("by_organizationId_userPhone", (q) =>
          q.eq("organizationId", args.organizationId).eq("userPhone", args.userPhone!),
        )
        .order("desc")
        .take(limit);
    }

    const q = ctx.db
      .query("org_whatsapp_conversations")
      .withIndex("by_organizationId", (q) =>
        q.eq("organizationId", args.organizationId),
      );

    if (args.status) {
      return await q
        .filter((f) => f.eq(f.field("status"), args.status))
        .order("desc")
        .take(limit);
    }

    return await q.order("desc").take(limit);
  },
});

/**
 * Get an org-level WhatsApp conversation by ID
 * Used by the adapter for direct ID lookups.
 */
export const getOrgConversationById = query({
  args: { id: v.string() },
  handler: async (ctx, args) => {
    try {
      return await ctx.db.get(args.id as any);
    } catch {
      return null;
    }
  },
});

/**
 * Get messages for an org-level WhatsApp conversation
 * Used by the unified webhook to load conversation history.
 */
export const getOrgMessages = query({
  args: {
    conversationId: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 100;
    return await ctx.db
      .query("org_whatsapp_messages")
      .withIndex("by_conversationId", (q) =>
        q.eq("conversationId", args.conversationId),
      )
      .order("asc")
      .take(limit);
  },
});

/**
 * Get unanswered questions for an organization.
 * Optionally filter by status ('open' | 'suggested' | 'resolved').
 */
export const getUnansweredQuestions = query({
  args: {
    organizationId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit || 50;

    if (args.status) {
      return await ctx.db
        .query("unanswered_questions")
        .withIndex("by_organizationId_status", (q) =>
          q
            .eq("organizationId", args.organizationId)
            .eq("status", args.status!),
        )
        .order("desc")
        .take(limit);
    }

    return await ctx.db
      .query("unanswered_questions")
      .withIndex("by_organizationId", (q) =>
        q.eq("organizationId", args.organizationId),
      )
      .order("desc")
      .take(limit);
  },
});

/**
 * Get suggested FAQs for an organization.
 * Optionally filter by status ('pending' | 'approved' | 'rejected').
 * Phase 7: FAQ auto-suggestion system.
 */
export const getSuggestedFaqs = query({
  args: {
    organizationId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit || 20;

    if (args.status) {
      return await ctx.db
        .query("suggested_faqs")
        .withIndex("by_organizationId_status", (q) =>
          q
            .eq("organizationId", args.organizationId)
            .eq("status", args.status!),
        )
        .order("desc")
        .take(limit);
    }

    return await ctx.db
      .query("suggested_faqs")
      .withIndex("by_organizationId", (q) =>
        q.eq("organizationId", args.organizationId),
      )
      .order("desc")
      .take(limit);
  },
});

/**
 * Get cross-sector common question patterns for a given sector.
 * Phase 7: FAQ auto-suggestion system.
 */
export const getSectorCommonQuestions = query({
  args: {
    sector: v.string(),
    limit: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("sector_common_questions")
      .withIndex("by_sector", (q) => q.eq("sector", args.sector))
      .order("desc")
      .take(args.limit || 50);
  },
});

/**
 * Get language preference for a user in an org.
 */
export const getLanguagePreference = query({
  args: { organizationId: v.string(), userPhone: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("user_language_preferences")
      .withIndex("by_organizationId_userPhone", (q) =>
        q.eq("organizationId", args.organizationId).eq("userPhone", args.userPhone),
      )
      .first();
  },
});
