"use client";

import { apiFetch } from "@/lib/csrf/client";
import { FREE_SCAN_LIMIT } from "@/lib/limits";

export interface SessionUser {
  id: string;
  email: string | null;
  name: string | null;
  plan: string;
  isPro: boolean;
  isGuest: boolean;
  emailVerified: boolean;
  launchBonus: boolean;
  freeScanAllowance: number;
  scanCount: number;
}

export interface SessionQuota {
  isPro: boolean;
  scanCount: number;
  scanLimit: number;
  launchBonus: boolean;
}

export async function getSessionUser(): Promise<SessionUser | null> {
  if (typeof window === "undefined") return null;
  try {
    const res = await apiFetch("/api/auth/session", { cache: "no-store" });
    if (!res.ok) return null;
    const data = await res.json();
    const user = data?.user as SessionUser | undefined;
    if (!user?.id) return null;
    return {
      id: user.id,
      email: user.email ?? null,
      name: user.name ?? null,
      plan: user.plan ?? "free",
      // Trust the server's isPro verdict as-is — it already accounts for
      // expiresAt, so a plan that's merely non-"free" but past its period
      // end must NOT be treated as Pro here.
      isPro: Boolean(user.isPro),
      isGuest: Boolean(user.isGuest),
      emailVerified: Boolean(user.emailVerified),
      launchBonus: Boolean(user.launchBonus),
      freeScanAllowance:
        typeof user.freeScanAllowance === "number" ? user.freeScanAllowance : FREE_SCAN_LIMIT,
      scanCount: Number(user.scanCount ?? 0),
    };
  } catch {
    return null;
  }
}

export async function getSessionQuota(): Promise<SessionQuota> {
  const user = await getSessionUser();
  if (!user) {
    return {
      isPro: false,
      scanCount: 0,
      scanLimit: FREE_SCAN_LIMIT,
      launchBonus: false,
    };
  }
  return {
    isPro: user.isPro,
    scanCount: user.scanCount,
    scanLimit: user.isPro ? Number.POSITIVE_INFINITY : user.freeScanAllowance,
    launchBonus: user.launchBonus,
  };
}
