import { notFound } from 'next/navigation';
import { eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { isInvoicesModuleEnabled } from '@/lib/services/invoices-module.service';
import { ModuleDisabledPage } from '@/components/shared/module-disabled-page';

interface InvoicesLayoutProps {
  children: React.ReactNode;
  params: Promise<{ portSlug: string }>;
}

/**
 * Layout-level gate for the standalone `/invoices` flow (list, new,
 * detail, upload-receipts). Default is OFF: the canonical "money
 * received" path in this CRM is the per-interest Payments tab; the
 * standalone invoicing surface only matters when an operator wants to
 * generate client-facing invoices from the CRM itself (rare). Admins
 * can opt in from Admin → Operations.
 *
 * Existing invoice rows are preserved when the module is disabled —
 * the API endpoints still respond so historical PDF links / webhook
 * callbacks keep resolving. Only the UI is hidden.
 */
export default async function InvoicesLayout({ children, params }: InvoicesLayoutProps) {
  const { portSlug } = await params;
  const port = await db.query.ports.findFirst({
    where: eq(portsTable.slug, portSlug),
    columns: { id: true },
  });
  // Fail closed: an unresolved slug means the port doesn't exist (or the
  // user mistyped one) — 404 rather than silently rendering the gated
  // subtree without a module check.
  if (!port) notFound();
  const enabled = await isInvoicesModuleEnabled(port.id);
  if (enabled) return children;
  return (
    <ModuleDisabledPage
      moduleName="Standalone invoicing"
      description="The standalone /invoices flow is turned off for this port. The canonical money-received path here is the per-interest Payments tab — that's where to record deposits and balance payments. Existing invoice rows are preserved and will reappear when the module is re-enabled."
      settingsHref={`/${portSlug}/admin/settings`}
      fallbackHref={`/${portSlug}/dashboard`}
    />
  );
}
