import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth/session";
import { FREE_SCAN_LIMIT, LAUNCH_BONUS_SCANS } from "@/lib/limits";
import { isProActive } from "@/lib/billing/access";

export const runtime = "nodejs";
export const dynamic = "force-dynamic";

/** Who am I? Returns `{ user: null }` when signed out — never an error. */
export async function GET(request: Request) {
  try {
    const user = await getCurrentUser(request);
    if (!user) return NextResponse.json({ user: null });

    const isPro = isProActive(user);

    return NextResponse.json({
      user: {
        id: user.id,
        email: user.email,
        name: user.name,
        plan: user.plan,
        isGuest: user.isGuest,
        isPro,
        cancelAtPeriodEnd: Boolean(user.cancelAtPeriodEnd),
        emailVerified: Boolean(user.emailVerifiedAt),
        launchBonus: Boolean(user.launchBonus),
        freeScanAllowance: user.launchBonus ? LAUNCH_BONUS_SCANS : FREE_SCAN_LIMIT,
        scanCount: Number(user.scanCount ?? 0),
        company: user.company ?? null,
        useCase: user.useCase ?? null,
        monthlyVolume: user.monthlyVolume ?? null,
        exportFormat: user.exportFormat ?? null,
        mainPainPoint: user.mainPainPoint ?? null,
        referralSource: user.referralSource ?? null,
        expiresAt: user.expiresAt?.toISOString() ?? null,
        createdAt: user.createdAt?.toISOString() ?? null,
        onboardingCompletedAt: user.onboardingCompletedAt?.toISOString() ?? null,
      },
    });
  } catch {
    // Database down: treat as signed out rather than breaking the shell.
    return NextResponse.json({ user: null });
  }
}
