import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { redirect } from "next/navigation";
import { SitesTable } from "./sites-table";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Sites" };

export default async function SitesPage() {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_sites")) redirect("/dashboard");

  const sites = await db.site.findMany({
    orderBy: { name: "asc" },
    include: {
      _count: { select: { inventory: true } },
    },
  });

  const canEdit = session.user.role === "ADMIN";

  return (
    <SitesTable
      canEdit={canEdit}
      sites={sites.map((s) => ({
        id: s.id,
        code: s.code,
        name: s.name,
        address: s.address ?? null,
        latitude: s.latitude ?? null,
        longitude: s.longitude ?? null,
        isActive: s.isActive,
        inventoryCount: s._count.inventory,
      }))}
    />
  );
}
