/**
 * Quotation Settings API
 * GET  - Get or create default settings
 * PATCH - Update settings
 */

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 * as settingsService from "@/lib/services/quotation-settings.service";
import { updateQuotationSettingsSchema } from "@/lib/validators/quotation-settings.validator";
import { getDataSource } from "@/lib/data-source";

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

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);

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

        let settings = await convexQuery("quotations/queries:getSettings", {
          userId: effectiveUserId,
        });

        // Lazy-create defaults if no settings exist (mirrors Prisma getOrCreate)
        if (!settings) {
          settings = await convexMutation(
            "quotations/mutations:upsertSettings",
            { userId: effectiveUserId },
          );
        }

        return NextResponse.json({
          success: true,
          settings: settings as Record<string, unknown>,
        });
      } catch (error) {
        log.warn("[Convex fallback] settings GET:", error);
        // Fall through to Prisma path
      }
    }

    // ── Prisma path ──────────────────────────────────────────────────
    const settings = await settingsService.getOrCreateSettings(effectiveUserId);
    return NextResponse.json({ success: true, settings });
  } catch (error) {
    log.error("Failed to get quotation settings", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export const PATCH = 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();
    const parsed = updateQuotationSettingsSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json(
        {
          success: false,
          error: "Invalid input",
          details: parsed.error.flatten(),
        },
        { status: 400 },
      );
    }

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

        const settings = await convexMutation(
          "quotations/mutations:upsertSettings",
          {
            userId: effectiveUserId,
            ...parsed.data,
            // Convert null values to undefined (Convex doesn't accept null for optional fields)
            penaltyMaxAmount: parsed.data.penaltyMaxAmount ?? undefined,
            companyName: parsed.data.companyName ?? undefined,
            companyLogo: parsed.data.companyLogo ?? undefined,
            footerText: parsed.data.footerText ?? undefined,
          },
        );

        return NextResponse.json({
          success: true,
          settings: settings as Record<string, unknown>,
        });
      } catch (error) {
        log.warn("[Convex fallback] settings PATCH:", error);
        // Fall through to Prisma path
      }
    }

    // ── Prisma path ──────────────────────────────────────────────────
    const settings = await settingsService.updateSettings(
      effectiveUserId,
      parsed.data,
    );
    return NextResponse.json({ success: true, settings });
  } catch (error) {
    log.error("Failed to update quotation settings", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
});
