/**
 * Recurring Quotation Template by ID API
 * GET - Get single template with items
 * PATCH - Update 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("RecurringQuotationByIdAPI");

type RouteContext = { params: Promise<{ id: string }> };

export async function GET(request: NextRequest, context: RouteContext) {
  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 { id } = await context.params;

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

        const template = await convexQuery(
          "quotations/queries:getRecurringById",
          { id: id as any },
        );

        if (template) {
          const t = template as any;
          if (t.userId !== effectiveUserId) {
            return NextResponse.json(
              { success: false, error: "Template not found" },
              { status: 404 },
            );
          }
          return NextResponse.json({ success: true, template });
        }

        return NextResponse.json(
          { success: false, error: "Template not found" },
          { status: 404 },
        );
      } catch (error) {
        console.error("[Convex fallback] recurring get by id:", error);
      }
    }

    const template = await recurringService.getRecurringTemplate(
      effectiveUserId,
      id,
    );
    if (!template) {
      return NextResponse.json(
        { success: false, error: "Template not found" },
        { status: 404 },
      );
    }

    return NextResponse.json({ success: true, template });
  } catch (error) {
    log.error("Failed to get recurring template", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export const PATCH = withCSRF(
  async (request: NextRequest, context: RouteContext) => {
    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 { id } = await context.params;
      const body = await request.json();

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

          const template = await convexMutation(
            "quotations/mutations:updateRecurring",
            {
              id: id as any,
              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,
              endDate: body.endDate
                ? new Date(body.endDate).getTime()
                : undefined,
              maxOccurrences: body.maxOccurrences,
              autoSend: body.autoSend,
              items: body.items,
            },
          );

          if (!template) {
            return NextResponse.json(
              { success: false, error: "Template not found" },
              { status: 404 },
            );
          }

          return NextResponse.json({ success: true, template });
        } catch (error) {
          console.error("[Convex fallback] recurring update:", error);
        }
      }

      const template = await recurringService.updateRecurringTemplate(
        effectiveUserId,
        id,
        body,
      );

      if (!template) {
        return NextResponse.json(
          { success: false, error: "Template not found" },
          { status: 404 },
        );
      }

      return NextResponse.json({ success: true, template });
    } catch (error) {
      log.error("Failed to update recurring template", error);
      return NextResponse.json(
        { success: false, error: "Internal server error" },
        { status: 500 },
      );
    }
  },
);
