import { prisma } from "@/lib/prisma";
import { ensureLicenseForAgency } from "@/lib/license";
import AgencyForm from "./AgencyForm";
import AgenciesList from "./AgenciesList";

export default async function AgenciesPage() {
  const licenses = await prisma.license.findMany({
    where: { active: true },
    orderBy: { maxTravelers: "asc" },
  });

  const all = await prisma.agency.findMany({ select: { id: true } });
  await Promise.all(all.map((a) => ensureLicenseForAgency(a.id)));

  const agencies = await prisma.agency.findMany({
    orderBy: { createdAt: "desc" },
    include: {
      license: true,
      users: { where: { role: "AGENCY" }, take: 1, select: { email: true } },
      _count: { select: { travelers: true, users: true } },
    },
  });

  const agencyRows = agencies.map((a) => ({
    ...a,
    loginEmail: a.users[0]?.email ?? null,
  }));

  return (
    <div className="space-y-6">
      <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <div>
          <h1 className="text-2xl font-bold">Agencias</h1>
          <p className="text-slate-500">Registra y administra las agencias de viaje.</p>
        </div>
        <AgencyForm licenses={licenses} />
      </div>

      <AgenciesList agencies={agencyRows} licenses={licenses} />
    </div>
  );
}
