import { AppShell } from "@/components/app-shell"
import { SiteHeader } from "@/components/site-header"
import { requireStaffSession } from "@/lib/auth-server"
import { DEFAULT_TENANT_ID } from "@/lib/constants"
import { AdminCompaniesManager } from "@/components/admin/companies/admin-companies-manager"
import { fetchCompaniesByTenant, normalizeCompany } from "@/server/company-service"

export const runtime = "nodejs"
export const dynamic = "force-dynamic"

export default async function AdminCompaniesPage({
  searchParams,
}: { searchParams: Promise<Record<string, string | string[] | undefined>> }) {
  const session = await requireStaffSession()
  const tenantId = session.user.tenantId ?? DEFAULT_TENANT_ID
  const params = await searchParams
  const autoOpenCreateCompany = params.quick === "new-company"
  const companies = (await fetchCompaniesByTenant(tenantId)).map(normalizeCompany)
  return (
    <AppShell
      header={
        <SiteHeader title="Empresas" lead="Gerencie os dados cadastrais das empresas atendidas." />
      }
    >
      <div className="mx-auto w-full max-w-7xl px-4 md:px-8 lg:px-10">
        <AdminCompaniesManager
          initialCompanies={companies}
          tenantId={tenantId}
          autoOpenCreate={autoOpenCreateCompany}
        />
      </div>
    </AppShell>
  )
}
