import type { APIRoute } from "astro";
import { prisma } from "../../lib/prisma";
import { createSession, sessionCookieFor, verifyPassword } from "../../lib/auth";

export const prerender = false;

export const POST: APIRoute = async ({ request }) => {
  try {
    const body = await request.json();
    const identifier = String(body?.username || body?.email || "")
      .trim()
      .toLowerCase();
    const password = String(body?.password || "");

    if (!identifier || !password) {
      return Response.json(
        { success: false, message: "Credenciales requeridas" },
        { status: 400 }
      );
    }

    const admin = await prisma.admin.findFirst({
      where: {
        OR: [
          { username: { equals: identifier, mode: "insensitive" } },
          { email: { equals: identifier, mode: "insensitive" } },
        ],
      },
    });

    if (
      !admin ||
      !admin.activo ||
      !admin.password_hash ||
      !verifyPassword(password, admin.password_hash)
    ) {
      return Response.json(
        { success: false, message: "Credenciales inválidas" },
        { status: 401 }
      );
    }

    await prisma.admin.update({
      where: { id: admin.id },
      data: { ultimo_acceso: new Date() },
    });

    const token = await createSession(admin.id);

    return new Response(JSON.stringify({ success: true }), {
      status: 200,
      headers: {
        "Content-Type": "application/json",
        "Set-Cookie": sessionCookieFor(token),
      },
    });
  } catch (error) {
    console.error("Error en /api/admin/auth/login:", error);
    return Response.json(
      { success: false, message: "Error en el login" },
      { status: 500 }
    );
  }
};
