import { redirect } from 'next/navigation';
import { headers } from 'next/headers';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { QueryProvider } from '@/providers/query-provider';
import { PortProvider } from '@/providers/port-provider';
import { eq } from 'drizzle-orm';

/**
 * Minimal layout for the mobile receipt-scanner PWA. No sidebar, no
 * topbar — the scanner is its own contained surface. Adds the PWA
 * manifest link + theme color so iOS/Android pick up "Add to Home
 * Screen". Auth check matches the dashboard layout so unauthorized
 * users still bounce to /login.
 */
export default async function ScannerLayout({
  children,
  params,
}: {
  children: React.ReactNode;
  params: Promise<{ portSlug: string }>;
}) {
  const session = await auth.api.getSession({ headers: await headers() });
  if (!session?.user) redirect('/login');

  const { portSlug } = await params;
  const port = await db.query.ports.findFirst({
    where: eq(portsTable.slug, portSlug),
  });
  if (!port) redirect('/login');

  return (
    <QueryProvider>
      <PortProvider ports={port ? [port] : []} defaultPortId={port?.id ?? null}>
        <head>
          <link rel="manifest" href={`/${portSlug}/scan/manifest.webmanifest`} />
          <meta name="theme-color" content="#3a7bc8" />
          <meta name="mobile-web-app-capable" content="yes" />
          <meta name="apple-mobile-web-app-capable" content="yes" />
          <meta name="apple-mobile-web-app-status-bar-style" content="default" />
          <meta name="apple-mobile-web-app-title" content="PN Scanner" />
          <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
        </head>
        <div className="min-h-[100dvh] bg-background">{children}</div>
      </PortProvider>
    </QueryProvider>
  );
}
