/**
 * Quotation Checkout API
 * POST - Create a Stripe checkout session for a quotation
 *
 * Note: Stripe checkout session creation stays on Prisma path regardless of
 * data-source setting (rule 4). Convex branch validates ownership via Convex
 * but delegates to the same Stripe service for session creation.
 */

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 { createQuotationCheckoutSession } from "@/lib/services/quotation-payments.service";
import { getDataSource } from "@/lib/data-source";

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

export const POST = withCSRF(
  async (
    request: NextRequest,
    context: { params: Promise<{ id: string }> },
  ) => {
    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: quotationId } = await context.params;

      const body = await request.json();
      const appUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:9000";
      const successUrl =
        body.successUrl ||
        `${appUrl}/dashboard/quotations/${quotationId}?payment=success`;
      const cancelUrl =
        body.cancelUrl ||
        `${appUrl}/dashboard/quotations/${quotationId}?payment=cancelled`;

      // Convex pre-validation: verify quotation exists and ownership
      if (getDataSource("quotations") === "convex") {
        try {
          const { convexQuery } = await import("@/lib/convex-client");
          const quotation = await convexQuery(
            "quotations/queries:getByUserAndId",
            { userId: effectiveUserId, quotationId },
          );
          if (!quotation) {
            return NextResponse.json(
              { success: false, error: "Quotation not found" },
              { status: 404 },
            );
          }
          const q = quotation as Record<string, unknown>;
          const remaining =
            ((q.total as number) ?? 0) +
            ((q.penaltyAmount as number) ?? 0) -
            ((q.amountPaid as number) ?? 0);
          if (remaining <= 0) {
            return NextResponse.json(
              { success: false, error: "Quotation is already fully paid" },
              { status: 400 },
            );
          }
        } catch (error) {
          log.warn("[Convex fallback] checkout pre-validation:", error);
          // Fall through to Prisma path
        }
      }

      // Stripe checkout session creation always uses Prisma service (rule 4)
      const result = await createQuotationCheckoutSession(
        effectiveUserId,
        quotationId,
        successUrl,
        cancelUrl,
      );

      return NextResponse.json({ success: true, ...result });
    } catch (error) {
      const message =
        error instanceof Error ? error.message : "Internal server error";
      const status = message.includes("not found")
        ? 404
        : message.includes("already fully paid")
          ? 400
          : 500;
      log.error("Failed to create checkout session", error);
      return NextResponse.json({ success: false, error: message }, { status });
    }
  },
);
