/**
 * Quotations API
 * GET - List quotations with filters
 * POST - Create a new quotation
 *
 * Convex-first with Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
// CSRF validated inline for development bypass
import { logger } from "@/lib/logger";
import { createQuotationSchema } from "@/lib/validators/quotations.validator";
import { convexQuery } from "@/lib/convex-client";
import { ConvexHttpClient } from "convex/browser";
const log = logger.scope("QuotationsAPI");

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    // Convex-first
    try {
      const effectiveUserId = await getEffectiveOwnerId(user.userId);
      const status = request.nextUrl.searchParams.get("status") ?? undefined;
      const result = await convexQuery("quotations/queries:getQuotations", {
        userId: effectiveUserId,
        status,
        limit: 50,
      });
      if (result !== null) {
        // Map Convex _id to id for frontend compatibility
        const quotations = (result as Record<string, unknown>[]).map((q) => ({
          ...q,
          id: q._id,
        }));
        return NextResponse.json({ quotations, success: true });
      }
    } catch (convexErr) {
      log.warn(
        "Convex quotations query failed, falling back to Prisma",
        convexErr,
      );
    }

    // Prisma fallback — return empty (Prisma service not wired here)
    return NextResponse.json({ quotations: [], success: true });
  } catch (error) {
    log.error("Failed to list quotations", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  // CSRF validation (skip in development for debugging)
  if (process.env.NODE_ENV !== "development") {
    const { validateCSRFToken } = await import("@/lib/csrf");
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { error: "Invalid or missing CSRF token" },
        { status: 403 },
      );
    }
  }
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    log.info("Quotation create - auth resolved", { userId: user.userId, effectiveUserId });
    const body = await request.json();
    log.info("Quotation create - body", { title: body.title, itemCount: body.items?.length });
    const parsed = createQuotationSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid input",
          details: parsed.error.flatten(),
        },
        { status: 400 },
      );
    }

    // Convex-first
    try {
      const items = (parsed.data.items ?? []).map((item) => ({
        description: item.description,
        quantity: item.quantity,
        unitPrice: item.unitPrice,
      }));

      const mutationArgs = {
        userId: effectiveUserId,
        customerId: parsed.data.customerId ?? undefined,
        title: parsed.data.title,
        notes: parsed.data.notes ?? undefined,
        currency: parsed.data.currency ?? undefined,
        taxRate: parsed.data.taxRate ?? undefined,
        discountRate: parsed.data.discountRate ?? undefined,
        validUntil: parsed.data.validUntil
          ? new Date(parsed.data.validUntil).getTime()
          : undefined,
        items: items.length > 0 ? items : undefined,
      };
      const convexUrl = process.env.NEXT_PUBLIC_CONVEX_URL || process.env.CONVEX_URL;
      if (!convexUrl) {
        return NextResponse.json(
          { success: false, error: "CONVEX_URL not configured" },
          { status: 503 },
        );
      }

      const client = new ConvexHttpClient(convexUrl);
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const quotationId = await (client.mutation as any)(
        "quotations/mutations:createQuotation" as any,
        mutationArgs,
      );

      // Always auto-send when customer exists
      if (parsed.data.customerId) {
        try {
          // Update status to SENT
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          await (client.mutation as any)(
            "quotations/mutations:updateQuotation" as any,
            { id: quotationId, status: "SENT" },
          );

          // Fetch customer for email
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          const customer = await (client.query as any)(
            "customers/queries:getCustomerById" as any,
            { id: parsed.data.customerId, userId: effectiveUserId },
          );

          if (customer?.email) {
            const currency = parsed.data.currency || "QAR";
            const itemRows = items
              .map(
                (item) =>
                  `<tr>
                    <td style="padding:8px;border-bottom:1px solid #eee">${item.description}</td>
                    <td style="padding:8px;border-bottom:1px solid #eee;text-align:center">${item.quantity}</td>
                    <td style="padding:8px;border-bottom:1px solid #eee;text-align:right">${item.unitPrice.toFixed(2)}</td>
                    <td style="padding:8px;border-bottom:1px solid #eee;text-align:right">${(item.quantity * item.unitPrice).toFixed(2)}</td>
                  </tr>`,
              )
              .join("");

            // eslint-disable-next-line @typescript-eslint/no-explicit-any
            const created = await (client.query as any)(
              "quotations/queries:getById" as any,
              { id: quotationId },
            );
            const total = (created?.total || 0).toFixed(2);

            const { sendEmail } = await import("@/lib/email");
            await sendEmail(customer.email, {
              subject: `Quotation ${created?.quotationNumber || ""} — ${parsed.data.title}`,
              html: `
                <div style="font-family:Arial,sans-serif;max-width:600px;margin:0 auto;padding:20px">
                  <h2 style="color:#1a1a1a">Quotation ${created?.quotationNumber || ""}</h2>
                  <p>Dear ${customer.name || "Customer"},</p>
                  <p>Please find your quotation below:</p>
                  <table style="width:100%;border-collapse:collapse;margin:16px 0">
                    <thead><tr style="background:#f8f8f8">
                      <th style="padding:8px;text-align:left;border-bottom:2px solid #ddd">Description</th>
                      <th style="padding:8px;text-align:center;border-bottom:2px solid #ddd">Qty</th>
                      <th style="padding:8px;text-align:right;border-bottom:2px solid #ddd">Unit Price</th>
                      <th style="padding:8px;text-align:right;border-bottom:2px solid #ddd">Total</th>
                    </tr></thead>
                    <tbody>${itemRows}</tbody>
                  </table>
                  <p style="font-size:18px;font-weight:bold;color:#1a1a1a">Total: ${currency} ${total}</p>
                  <p style="color:#666;font-size:14px;margin-top:24px">If you have any questions, please contact us.</p>
                </div>
              `,
            });
            log.info("Quotation sent immediately", { quotationId, to: customer.email });
          }
        } catch (sendErr) {
          log.warn("Failed to send quotation immediately, saved as DRAFT", sendErr);
        }
      }

      return NextResponse.json(
        { success: true, quotation: { id: quotationId } },
        { status: 201 },
      );
    } catch (convexErr) {
      log.error("Convex quotation create failed", convexErr);
      return NextResponse.json(
        { success: false, error: `Convex error: ${convexErr instanceof Error ? convexErr.message : String(convexErr)}` },
        { status: 500 },
      );
    }
  } catch (error) {
    log.error("Failed to create quotation", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
