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

/**
 * Get quotations for a user (paginated)
 * Phase 7: Leads, Quotations, Expenses
 */
export const getQuotations = 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("quotations")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .order("desc")
      .take(limit);
  },
});

/**
 * Get a single quotation by ID
 * Phase 7: Leads, Quotations, Expenses
 */
export const getById = query({
  args: { id: v.id("quotations") },
  handler: async (ctx, args) => {
    return await ctx.db.get(args.id);
  },
});

/**
 * Get line items for a quotation
 * Phase 7: Leads, Quotations, Expenses
 */
export const getItems = query({
  args: { quotationId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("quotation_items")
      .withIndex("by_quotationId", (q) => q.eq("quotationId", args.quotationId))
      .collect();
  },
});

/**
 * Get payment records for a quotation
 * Phase 7: Leads, Quotations, Expenses
 */
export const getPayments = query({
  args: { quotationId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("quotation_payments")
      .withIndex("by_quotationId", (q) => q.eq("quotationId", args.quotationId))
      .collect();
  },
});

/**
 * Get a quotation by prismaId (or Convex _id) scoped to a user for ownership verification
 * WU-07: Quotation core routes wiring
 */
export const getByUserAndId = query({
  args: {
    userId: v.string(),
    quotationId: v.string(),
  },
  handler: async (ctx, args) => {
    // Try finding by prismaId first (most common when migrating from Prisma)
    const byPrismaId = await ctx.db
      .query("quotations")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .filter((f) => f.eq(f.field("prismaId"), args.quotationId))
      .first();

    if (byPrismaId) return byPrismaId;

    // Fallback: try as a Convex _id
    try {
      const byId = await ctx.db.get(args.quotationId as never);
      if (byId && (byId as { userId: string }).userId === args.userId) {
        return byId;
      }
    } catch {
      // Invalid ID format — not found
    }

    return null;
  },
});

/**
 * Get a quotation with its items by user and ID (for resend/send with full data)
 * WU-07: Quotation core routes wiring
 */
export const getWithItemsByUserAndId = query({
  args: {
    userId: v.string(),
    quotationId: v.string(),
  },
  handler: async (ctx, args) => {
    // Find quotation by prismaId or Convex _id
    let quotation = await ctx.db
      .query("quotations")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .filter((f) => f.eq(f.field("prismaId"), args.quotationId))
      .first();

    if (!quotation) {
      try {
        const byId = await ctx.db.get(args.quotationId as never);
        if (byId && (byId as { userId: string }).userId === args.userId) {
          quotation = byId as unknown as typeof quotation;
        }
      } catch {
        // Invalid ID format
      }
    }

    if (!quotation) return null;

    // Get items sorted by sortOrder
    const qId = quotation._id as unknown as string;
    const items = await ctx.db
      .query("quotation_items")
      .withIndex("by_quotationId_sortOrder", (q) => q.eq("quotationId", qId))
      .collect();

    return { ...quotation, items };
  },
});

/**
 * Get quotation settings for a user
 * WU-07: Quotation core routes wiring
 */
export const getSettings = query({
  args: { userId: v.string() },
  handler: async (ctx, args) => {
    return await ctx.db
      .query("quotation_settings")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId))
      .first();
  },
});

/**
 * Get deals pipeline for a user
 * Phase 7: Leads, Quotations, Expenses
 */
export const getDeals = query({
  args: {
    userId: v.string(),
    stage: v.optional(v.string()),
  },
  handler: async (ctx, args) => {
    const q = ctx.db
      .query("deals")
      .withIndex("by_userId", (q) => q.eq("userId", args.userId));

    if (args.stage) {
      return await q
        .filter((f) => f.eq(f.field("stage"), args.stage))
        .collect();
    }

    return await q.collect();
  },
});

// ═══════════════════════════════════════════════════════════════════════
// Recurring Quotation Queries — Phase 7 gap-fill
// ═══════════════════════════════════════════════════════════════════════

/**
 * Get recurring quotation schedules for a user
 */
export const getRecurringQuotations = query({
  args: {
    userId: v.string(),
    status: v.optional(v.string()),
    limit: v.optional(v.number()),
    offset: v.optional(v.number()),
  },
  handler: async (ctx, args) => {
    const limit = args.limit ?? 20;

    let results;
    if (args.status) {
      results = await ctx.db
        .query("quotation_recurring_templates")
        .withIndex("by_userId_status", (q) =>
          q
            .eq("userId", args.userId)
            .eq(
              "status",
              args.status as "ACTIVE" | "PAUSED" | "CANCELLED" | "COMPLETED",
            ),
        )
        .order("desc")
        .collect();
    } else {
      results = await ctx.db
        .query("quotation_recurring_templates")
        .withIndex("by_userId", (q) => q.eq("userId", args.userId))
        .order("desc")
        .collect();
    }

    const total = results.length;
    const offset = args.offset ?? 0;
    const paginated = results.slice(offset, offset + limit);

    // Fetch items for each template
    const templatesWithItems = await Promise.all(
      paginated.map(async (template) => {
        const items = await ctx.db
          .query("quotation_recurring_template_items")
          .withIndex("by_templateId", (q) =>
            q.eq("templateId", template._id as unknown as string),
          )
          .collect();
        return { ...template, items };
      }),
    );

    return { templates: templatesWithItems, total };
  },
});

/**
 * Get a single recurring quotation by ID
 */
export const getRecurringById = query({
  args: { id: v.id("quotation_recurring_templates") },
  handler: async (ctx, args) => {
    const template = await ctx.db.get(args.id);
    if (!template) return null;

    const items = await ctx.db
      .query("quotation_recurring_template_items")
      .withIndex("by_templateId", (q) =>
        q.eq("templateId", args.id as unknown as string),
      )
      .collect();

    return { ...template, items };
  },
});

/**
 * Get a quotation by its portal token (for public payment page)
 */
export const getQuotationByPortalToken = query({
  args: { portalToken: v.string() },
  handler: async (ctx, args) => {
    const quotations = await ctx.db
      .query("quotations")
      .withIndex("by_portalToken", (q) => q.eq("portalToken", args.portalToken))
      .take(1);

    if (quotations.length === 0) return null;

    const quotation = quotations[0];

    // Fetch items
    const items = await ctx.db
      .query("quotation_items")
      .withIndex("by_quotationId", (q) =>
        q.eq("quotationId", quotation._id as unknown as string),
      )
      .collect();

    // Fetch payments
    const payments = await ctx.db
      .query("quotation_payments")
      .withIndex("by_quotationId", (q) =>
        q.eq("quotationId", quotation._id as unknown as string),
      )
      .collect();

    return {
      ...quotation,
      items,
      payments,
    };
  },
});
