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

/**
 * Get user by n8nWebhookToken — used by server-tool token auth
 * Phase 6: WhatsApp & Voice Agents (gap-fill for WU-12)
 */
export const getUserByWebhookToken = query({
  args: { token: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("users")
      .withIndex("by_n8nWebhookToken", (q) =>
        q.eq("n8nWebhookToken", args.token),
      )
      .unique();
  },
});

/**
 * Get user by voiceAgentId — used by webhook to resolve agent owner
 * Phase 6: WhatsApp & Voice Agents (gap-fill for WU-12)
 */
export const getUserByVoiceAgentId = query({
  args: { voiceAgentId: v.string() },
  handler: async (ctx, args) => {
    // No dedicated index — filter scan (voice agent count is small)
    return await ctx.db
      .query("users")
      .filter((q) => q.eq(q.field("voiceAgentId"), args.voiceAgentId))
      .first();
  },
});

/**
 * Get user's voice agent provisioning info
 * Phase 6: WhatsApp & Voice Agents (gap-fill for WU-12)
 */
export const getUserVoiceAgent = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    // Look up by prismaId
    const user = await ctx.db
      .query("users")
      .filter((q) => q.eq(q.field("prismaId"), args.userId))
      .first();
    if (!user) return null;
    return {
      id: user.prismaId ?? user._id,
      voiceAgentId: user.voiceAgentId ?? null,
      voiceAgentConfig: user.voiceAgentConfig ?? null,
    };
  },
});

/**
 * Get voice conversation count for dashboard stats
 * Phase 6: WhatsApp & Voice Agents (gap-fill for WU-12)
 */
export const getVoiceConversationStats = query({
  args: {
    userId: v.string(),
    sinceTimestamp: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    let logs = await ctx.db
      .query("conversation_logs")
      .withIndex("by_userId_updatedAt", (q) => q.eq("userId", args.userId))
      .collect();

    // Filter to voice platform
    logs = logs.filter((l) => l.platform === "voice");

    if (args.sinceTimestamp) {
      logs = logs.filter((l) => l.createdAt >= args.sinceTimestamp!);
    }
    return { count: logs.length, logs };
  },
});

/**
 * Get conversation logs for a user (voice agent calls)
 * Phase 6: WhatsApp & Voice Agents
 */
export const getConversationLogs = query({
  args: {
    userId: v.string(),
    platform: v.optional(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("conversation_logs")
      .withIndex("by_userId_updatedAt", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get phone configuration for a user's voice agent
 * Phase 6: WhatsApp & Voice Agents
 */
export const getPhoneConfig = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("voice_agent_phone_config")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .unique();
  },
});

/**
 * Get knowledge base documents for a user
 * Phase 6: WhatsApp & Voice Agents
 */
export const getKBDocuments = query({
  args: {
    userId: v.string(),
    category: v.optional(v.string()),
    status: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    let results = await ctx.db
      .query("knowledge_base_documents")
      .withIndex("by_userId_status", (q) => q.eq("userId", args.userId))
      .collect();

    if (args.status) {
      results = results.filter((d) => d.status === args.status);
    }
    if (args.category) {
      results = results.filter((d) => d.category === args.category);
    }

    return results;
  },
});

/**
 * Get a single knowledge base document by its prismaId
 * Phase 6: WhatsApp & Voice Agents
 */
export const getKBDocumentById = query({
  args: { id: v.string() },
  handler: async (ctx, args) => {
    // Try as Convex _id first, fall back to prismaId scan
    let doc = null;
    try {
      doc = await ctx.db.get(args.id as any);
    } catch {
      /* not a valid Convex ID */
    }
    if (!doc) {
      doc = await ctx.db
        .query("knowledge_base_documents")
        .filter((q) => q.eq(q.field("prismaId"), args.id))
        .first();
    }
    return doc ?? null;
  },
});

/**
 * Get knowledge base settings by userId
 * Phase 6: WhatsApp & Voice Agents
 */
export const getKBSettingsByUserId = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("knowledge_base_settings")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .first();
  },
});

/**
 * Get knowledge base FAQs for a user with optional filters
 * Phase 6: WhatsApp & Voice Agents
 */
export const getKBFAQs = query({
  args: {
    userId: v.string(),
    category: v.optional(v.string()),
    isActive: v.optional(v.boolean()),
  },
  handler: async (ctx, args) => {
    let results = await ctx.db
      .query("knowledge_base_faqs")
      .withIndex("by_userId_isActive", (q) => q.eq("userId", args.userId))
      .collect();
    if (args.category) {
      results = results.filter((f) => f.category === args.category);
    }
    if (args.isActive !== undefined) {
      results = results.filter((f) => f.isActive === args.isActive);
    }
    return results;
  },
});

/**
 * Get knowledge base chunks by documentId
 * Phase 6: WhatsApp & Voice Agents
 */
export const getKBChunksByDocumentId = query({
  args: {
    documentId: v.string(),
  },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("knowledge_base_chunks")
      .withIndex("by_documentId_chunkIndex", (q) =>
        q.eq("documentId", args.documentId),
      )
      .collect();
  },
});
