import { NextResponse } from "next/server";
import { apiFetch, ApiError } from "@/lib/api/client";
import { getSession } from "@/lib/auth/session";

// Proxy vers POST /api/mobile/totp/disable.php — exige un code TOTP valide
// même pour désactiver (anti-vol de session : un attaquant qui a volé un
// cookie session ne peut pas désactiver le 2FA sans l'app authenticator).

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) {
    return NextResponse.json(
      { success: false, error: "Session expirée" },
      { status: 401 },
    );
  }

  let payload: { code?: unknown };
  try {
    payload = await request.json();
  } catch {
    return NextResponse.json(
      { success: false, error: "Requête invalide" },
      { status: 400 },
    );
  }

  const code = typeof payload.code === "string" ? payload.code.trim() : "";
  if (!/^\d{6}$/.test(code)) {
    return NextResponse.json(
      { success: false, error: "Code à 6 chiffres requis" },
      { status: 400 },
    );
  }

  try {
    const body = await apiFetch<{ success: boolean; message?: string }>(
      "/mobile/totp/disable.php",
      {
        method: "POST",
        token: session.token,
        body: { code },
      },
    );
    if (!body.success) {
      return NextResponse.json(
        { success: false, error: body.message ?? "Code invalide" },
        { status: 401 },
      );
    }
    return NextResponse.json({ success: true });
  } catch (err) {
    if (err instanceof ApiError && err.status === 401) {
      return NextResponse.json(
        { success: false, error: "Code TOTP invalide" },
        { status: 401 },
      );
    }
    if (err instanceof ApiError) {
      return NextResponse.json(
        { success: false, error: err.message ?? "Erreur backend" },
        { status: err.status },
      );
    }
    console.error("[auth/totp/disable] upstream error:", err);
    return NextResponse.json(
      { success: false, error: "Service d'authentification indisponible" },
      { status: 502 },
    );
  }
}
