import { auth } from "@/auth";
import { db } from "@/lib/db";
import { hasPermission } from "@/lib/permissions";
import { generateDownloadUrl } from "@/lib/storage";
import { redirect, notFound } from "next/navigation";
import { CompanyForm } from "../../company-form";
import type { Metadata } from "next";

export const metadata: Metadata = { title: "Edit Company" };

export default async function EditCompanyPage({ params }: { params: Promise<{ id: string }> }) {
  const session = await auth();
  if (!session?.user) redirect("/login");
  if (!hasPermission(session.user.role, "manage_vessels_accounts")) redirect("/dashboard");

  const { id } = await params;
  const c = await db.company.findUnique({ where: { id } });
  if (!c) notFound();

  return (
    <CompanyForm
      company={{
        id: c.id,
        name: c.name,
        code: c.code,
        gstNumber: c.gstNumber,
        address: c.address,
        telephone: c.telephone,
        mobile: c.mobile,
        email: c.email,
        invoiceEmail: c.invoiceEmail,
        invoiceAddress: c.invoiceAddress,
        logoUrl: c.logoKey ? await generateDownloadUrl(c.logoKey) : null,
        stampUrl: c.stampKey ? await generateDownloadUrl(c.stampKey) : null,
        isActive: c.isActive,
      }}
    />
  );
}
