import { redirect, forbidden } from "next/navigation";
import { NextResponse } from "next/server";
import type { Session } from "next-auth";
import { auth } from "@/auth";
import { canAccessBrigade, type Role } from "./roles";

/**
 * Vollständiger Guard-Satz (default-deny, Querschnittsstandard 1–3).
 *
 * - Server Components / Server Actions nutzen `requireSession`/`requireRole`/…
 *   (sie werfen `redirect("/login")` bzw. `forbidden()` → 403).
 * - API-Routen nutzen `apiAuth` / `apiRequireRole` / `apiRequireOwnBrigade`,
 *   die `NextResponse` mit 401/403 OHNE Fachdaten zurückgeben.
 */
export type AppSession = Session & {
  user: {
    id: string;
    role: Role;
    brigadeId: string | null;
    email: string;
    name: string;
  };
};

// ── Server Components / Server Actions ─────────────────────────────────────

export async function requireSession(): Promise<AppSession> {
  const s = await auth();
  if (!s?.user) redirect("/login");
  return s as AppSession;
}

export async function requireRole(...allowed: Role[]): Promise<AppSession> {
  const s = await requireSession();
  if (!allowed.includes(s.user.role)) forbidden(); // 403
  return s;
}

export async function requirePlatformAdmin(): Promise<AppSession> {
  return requireRole("platform_admin");
}

export async function requireWehrAdmin(): Promise<
  AppSession & { user: AppSession["user"] & { brigadeId: string } }
> {
  const s = await requireRole("wehr_admin");
  if (!s.user.brigadeId) forbidden();
  return s as AppSession & { user: AppSession["user"] & { brigadeId: string } };
}

export async function requireOwnBrigade(
  brigadeId: string,
): Promise<AppSession> {
  const s = await requireRole("wehr_admin", "platform_admin");
  if (!canAccessBrigade(s.user.role, s.user.brigadeId, brigadeId)) forbidden();
  return s;
}

// ── API-Routen (401/403 ohne Daten-Leak, Querschnittsstandard 2) ───────────

export type ApiAuthResult =
  | { ok: true; session: AppSession }
  | { ok: false; response: NextResponse };

const unauthorized = () =>
  NextResponse.json({ error: "Anmeldung erforderlich." }, { status: 401 });
const forbiddenResponse = () =>
  NextResponse.json({ error: "Keine Berechtigung." }, { status: 403 });

export async function apiAuth(): Promise<ApiAuthResult> {
  const s = await auth();
  if (!s?.user) return { ok: false, response: unauthorized() };
  return { ok: true, session: s as AppSession };
}

export async function apiRequireRole(
  ...allowed: Role[]
): Promise<ApiAuthResult> {
  const result = await apiAuth();
  if (!result.ok) return result;
  if (!allowed.includes(result.session.user.role)) {
    return { ok: false, response: forbiddenResponse() };
  }
  return result;
}

export async function apiRequireOwnBrigade(
  brigadeId: string,
): Promise<ApiAuthResult> {
  const result = await apiRequireRole("wehr_admin", "platform_admin");
  if (!result.ok) return result;
  if (
    !canAccessBrigade(
      result.session.user.role,
      result.session.user.brigadeId,
      brigadeId,
    )
  ) {
    return { ok: false, response: forbiddenResponse() };
  }
  return result;
}
