/**
 * Recurring Quotation Templates API
 * GET - List recurring templates with filters
 * POST - Create a new recurring template
 */

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";
import { withCSRF } from "@/lib/csrf";
import { logger } from "@/lib/logger";
import { getDataSource } from "@/lib/data-source";
import * as recurringService from "@/lib/services/quotation-recurring.service";

const log = logger.scope("RecurringQuotationsAPI");

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

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    const params = Object.fromEntries(request.nextUrl.searchParams.entries());

    const filters: {
      status?: "ACTIVE" | "PAUSED" | "CANCELLED" | "COMPLETED";
      page?: number;
      limit?: number;
    } = {};

    if (
      params.status &&
      ["ACTIVE", "PAUSED", "CANCELLED", "COMPLETED"].includes(params.status)
    ) {
      filters.status = params.status as
        | "ACTIVE"
        | "PAUSED"
        | "CANCELLED"
        | "COMPLETED";
    }
    if (params.page) filters.page = parseInt(params.page, 10);
    if (params.limit) filters.limit = parseInt(params.limit, 10);

    // ── Convex path ──────────────────────────────────────────────────
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexQuery } = await import("@/lib/convex-client");

        const page = filters.page ?? 1;
        const limit = Math.min(filters.limit ?? 20, 100);
        const offset = (page - 1) * limit;

        const result = await convexQuery(
          "quotations/queries:getRecurringQuotations",
          {
            userId: effectiveUserId,
            status: filters.status,
            limit,
            offset,
          },
        );

        if (result) {
          const { templates, total } = result as {
            templates: unknown[];
            total: number;
          };
          return NextResponse.json({
            success: true,
            templates,
            total,
            page,
            limit,
            totalPages: Math.ceil(total / limit),
          });
        }
      } catch (error) {
        console.error("[Convex fallback] recurring quotations list:", error);
      }
    }

    const result = await recurringService.listRecurringTemplates(
      effectiveUserId,
      filters,
    );
    return NextResponse.json({ success: true, ...result });
  } catch (error) {
    log.error("Failed to list recurring templates", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

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

    const effectiveUserId = await getEffectiveOwnerId(user.userId);
    const body = await request.json();

    // Basic validation
    if (
      !body.title ||
      !body.frequency ||
      !body.startDate ||
      !Array.isArray(body.items) ||
      body.items.length === 0
    ) {
      return NextResponse.json(
        {
          success: false,
          error: "title, frequency, startDate, and items are required",
        },
        { status: 400 },
      );
    }

    // ── Convex path ──────────────────────────────────────────────────
    if (getDataSource("quotations") === "convex") {
      try {
        const { convexMutation } = await import("@/lib/convex-client");

        const templateId = await convexMutation(
          "quotations/mutations:createRecurring",
          {
            userId: effectiveUserId,
            customerId: body.customerId,
            title: body.title,
            notes: body.notes,
            currency: body.currency,
            taxRate: body.taxRate,
            discountRate: body.discountRate,
            validDays: body.validDays,
            paymentDueDays: body.paymentDueDays,
            frequency: body.frequency,
            customIntervalDays: body.customIntervalDays,
            startDate: new Date(body.startDate).getTime(),
            endDate: body.endDate
              ? new Date(body.endDate).getTime()
              : undefined,
            maxOccurrences: body.maxOccurrences,
            autoSend: body.autoSend,
            items: body.items,
          },
        );

        return NextResponse.json(
          { success: true, template: { id: templateId } },
          { status: 201 },
        );
      } catch (error) {
        console.error("[Convex fallback] recurring create:", error);
      }
    }

    const template = await recurringService.createRecurringTemplate(
      effectiveUserId,
      body,
    );
    return NextResponse.json({ success: true, template }, { status: 201 });
  } catch (error) {
    log.error("Failed to create recurring template", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
});
