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

export const metadata: Metadata = { title: "Delivery Locations" };

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

  const [locations, companies] = await Promise.all([
    db.deliveryLocation.findMany({
      orderBy: [{ isActive: "desc" }, { createdAt: "desc" }],
      include: { company: { select: { name: true } } },
    }),
    db.company.findMany({ where: { isActive: true }, orderBy: { name: "asc" }, select: { id: true, name: true } }),
  ]);

  return (
    <DeliveryLocationsTable
      companies={companies}
      locations={locations.map((l) => ({
        id: l.id,
        companyId: l.companyId,
        companyName: l.company.name,
        address: l.address,
        isActive: l.isActive,
      }))}
    />
  );
}
