import { NextRequest, NextResponse } from "next/server";
import { db, isDatabaseAvailable } from "@/lib/db";
import { ensureDatabaseInitialized } from "@/lib/db/init";
import { users } from "@/lib/schema/db";
import { getCurrentUser } from "@/lib/auth/session";
import { eq } from "drizzle-orm";
import { sanitizeText } from "@/lib/ingest/sanitize";
import { MAX_JSON_BODY_BYTES } from "@/lib/limits";
import { readJsonSized } from "@/lib/http/requestSize";
import { requireCsrf } from "@/lib/auth/csrf";

export const runtime = "nodejs";

/**
 * POST /api/onboarding
 * Saves onboarding data (company, use case, referral source) for the
 * currently logged-in user and marks onboarding as completed.
 */
export async function POST(req: NextRequest) {
  try {
    const csrfBlocked = requireCsrf(req);
    if (csrfBlocked) return csrfBlocked;

    const user = await getCurrentUser(req);
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const parsed = await readJsonSized<{
      name?: string;
      company?: string;
      useCase?: string;
      monthlyVolume?: string;
      exportFormat?: string;
      mainPainPoint?: string;
      referralSource?: string;
    }>(req, MAX_JSON_BODY_BYTES);
    if (!parsed.ok) return parsed.response;
    const body = parsed.body ?? {};
    const { name, company, useCase, monthlyVolume, exportFormat, mainPainPoint, referralSource } = body;

    const dbAvailable = await isDatabaseAvailable();
    if (!dbAvailable) {
      return NextResponse.json(
        { error: "Database unavailable" },
        { status: 503 }
      );
    }

    await ensureDatabaseInitialized();

    // Sanitize before persist: markup / control chars / length caps per column
    // Non-string input is ignored; empty-after-sanitize values are not written.
    const sanitized = (v: unknown, cap: number): string | undefined =>
      typeof v === "string" && v.trim() !== ""
        ? sanitizeText(v, cap) || undefined
        : undefined;

    const cleanName = sanitized(name, 160);
    const cleanCompany = sanitized(company, 255);
    const cleanUseCase = sanitized(useCase, 100);
    const cleanMonthlyVolume = sanitized(monthlyVolume, 50);
    const cleanExportFormat = sanitized(exportFormat, 100);
    const cleanPainPoint = sanitized(mainPainPoint, 100);
    const cleanReferral = sanitized(referralSource, 100);

    const updates: Record<string, any> = {
      onboardingCompletedAt: new Date(),
      updatedAt: new Date(),
    };

    if (cleanName !== undefined) updates.name = cleanName;
    if (cleanCompany !== undefined) updates.company = cleanCompany;
    if (cleanUseCase !== undefined) updates.useCase = cleanUseCase;
    if (cleanMonthlyVolume !== undefined) updates.monthlyVolume = cleanMonthlyVolume;
    if (cleanExportFormat !== undefined) updates.exportFormat = cleanExportFormat;
    if (cleanPainPoint !== undefined) updates.mainPainPoint = cleanPainPoint;
    if (cleanReferral !== undefined) updates.referralSource = cleanReferral;

    await db.update(users).set(updates).where(eq(users.id, user.id));

    return NextResponse.json({ success: true });
  } catch (error: any) {
    console.error("POST /api/onboarding error:", error);
    return NextResponse.json(
      { error: error?.message || "Internal server error" },
      { status: 500 }
    );
  }
}
