import { NextRequest, NextResponse } from "next/server";
import { activeServers } from "@/lib/server/xtreamServers";

export const dynamic = "force-dynamic";

// UA de reproductor: muchos paneles Xtream bloquean el UA del navegador.
const PLAYER_UA = "IPTVSmartersPlayer";

async function checkServer(base: string, username: string, password: string) {
  const url = `${base.replace(/\/+$/, "")}/player_api.php?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`;
  try {
    const res = await fetch(url, {
      headers: { "User-Agent": PLAYER_UA, Accept: "application/json" },
      cache: "no-store",
      signal: AbortSignal.timeout(12000)
    });
    if (!res.ok) return null;
    const data = await res.json().catch(() => null);
    if (data && Number(data?.user_info?.auth) === 1) return data;
    return null;
  } catch {
    return null;
  }
}

export async function POST(request: NextRequest) {
  const body = await request.json().catch(() => ({}));
  const username = String(body.username ?? body.email ?? "").trim();
  const password = String(body.password ?? "");
  if (!username || !password) {
    return NextResponse.json({ error: "Usuario y contraseña requeridos." }, { status: 400 });
  }

  const servers = await activeServers();
  if (!servers.length) {
    return NextResponse.json({ error: "No hay servidores configurados en el panel." }, { status: 503 });
  }

  for (const srv of servers) {
    const info = await checkServer(srv.url, username, password);
    if (info) {
      return NextResponse.json({
        server: srv.url.replace(/\/+$/, ""),
        username,
        password,
        user_info: info.user_info ?? null,
        server_info: info.server_info ?? null
      });
    }
  }

  return NextResponse.json({ error: "Usuario o contraseña incorrectos, o suscripción vencida." }, { status: 401 });
}
