import { NextResponse } from "next/server";
import { cookies } from "next/headers";
import { apiFetch, ApiError } from "@/lib/api/client";
import { setSession } from "@/lib/auth/session";
import { env } from "@/lib/config";
import type { MobileLoginResponse, SuperAdminUser } from "@/lib/api/types";

// Identifiant device fixe pour le panel — tous les super-admins partagent ce
// device dans la table mobile_refresh_tokens, ce qui est OK : la table est
// indexée par hash + device_id, et un super-admin n'a pas besoin de tracking
// fin par appareil comme un technicien terrain.
const DEVICE_ID = "sysop-panel";
const DEVICE_NAME = "missioflow-SuperAdmin";

// Cookie temporaire qui transporte le challenge_token entre l'écran 1
// (email/password) et l'écran 2 (code TOTP). httpOnly pour que le JS ne
// puisse pas le lire (anti-XSS), TTL aligné sur le store backend (5 min).
const TOTP_CHALLENGE_COOKIE = "mf_totp_challenge";
const TOTP_CHALLENGE_TTL_SECONDS = 300;

export async function POST(request: Request) {
  let payload: { email?: unknown; password?: unknown };
  try {
    payload = await request.json();
  } catch {
    return NextResponse.json({ error: "Requête invalide" }, { status: 400 });
  }

  const email =
    typeof payload.email === "string" ? payload.email.trim() : "";
  const password =
    typeof payload.password === "string" ? payload.password : "";

  if (!email || !password) {
    return NextResponse.json(
      { error: "Email et mot de passe requis" },
      { status: 400 },
    );
  }

  // Endpoint mobile JWT : la réponse contient un access_token Bearer qui
  // permettra aux appels suivants de skipper le CSRF côté backend
  // (`ApiCsrf::skippingForMobileJwt()`). Cf handoff Q5.
  let body: MobileLoginResponse;
  try {
    body = await apiFetch<MobileLoginResponse>("/mobile/login.php", {
      method: "POST",
      body: {
        email,
        password,
        device_id: DEVICE_ID,
        device_name: DEVICE_NAME,
      },
    });
  } catch (err) {
    if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
      return NextResponse.json(
        { error: "Identifiants invalides" },
        { status: 401 },
      );
    }
    // Log toujours côté serveur pour debug (visible dans `docker service logs`).
    console.error("[auth/login] upstream error:", err);
    // En non-prod, on remonte le détail au client pour debug rapide.
    const debug = process.env.NODE_ENV !== "production";
    const payload: Record<string, unknown> = {
      error: "Service d'authentification indisponible",
    };
    if (debug && err instanceof ApiError) {
      payload.upstream_status = err.status;
      payload.upstream_payload = err.payload;
    } else if (debug && err instanceof Error) {
      payload.upstream_message = err.message;
    }
    return NextResponse.json(payload, { status: 502 });
  }

  if (!body.success || !body.data) {
    return NextResponse.json(
      { error: body.message ?? "Échec de l'authentification" },
      { status: 401 },
    );
  }

  // Branche 2FA : le backend a validé email/password et détecté que le
  // super-admin a `totp_enabled=1`. Il renvoie un challenge_token court-vie
  // au lieu de l'access_token. On le pose en cookie httpOnly et on demande
  // au client d'afficher l'écran code TOTP.
  if ("requires_totp" in body.data && body.data.requires_totp === true) {
    const store = await cookies();
    store.set(TOTP_CHALLENGE_COOKIE, body.data.challenge_token, {
      httpOnly: true,
      secure: env.isProduction,
      sameSite: "lax",
      path: "/",
      maxAge: TOTP_CHALLENGE_TTL_SECONDS,
    });
    return NextResponse.json({ success: true, requires_totp: true });
  }

  if (!body.data.access_token || !body.data.user) {
    return NextResponse.json(
      { error: body.message ?? "Échec de l'authentification" },
      { status: 401 },
    );
  }

  if (body.data.user.is_superadmin !== 1) {
    return NextResponse.json(
      { error: "Accès réservé aux super-administrateurs" },
      { status: 403 },
    );
  }

  const u = body.data.user;
  const normalizedUser: SuperAdminUser = {
    id: u.id,
    email: u.email,
    name: u.name,
    role: u.role,
    user_type: u.user_type,
    tenant_id: u.tenant_id,
    is_superadmin: true,
  };

  await setSession({
    token: body.data.access_token,
    refreshToken: body.data.refresh_token,
    user: normalizedUser,
  });
  return NextResponse.json({ success: true, user: normalizedUser });
}
