import type { Metadata, Viewport } from 'next';
import { notFound, redirect } from 'next/navigation';
import { headers } from 'next/headers';
import { and, eq } from 'drizzle-orm';

import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { userPortRoles, userProfiles } from '@/lib/db/schema/users';
import { QueryProvider } from '@/providers/query-provider';
import { PortProvider } from '@/providers/port-provider';

/**
 * Minimal layout for the mobile receipt-scanner PWA. No sidebar, no
 * topbar - the scanner is its own contained surface. PWA manifest +
 * iOS web-app meta tags are emitted via Next.js's metadata/viewport
 * exports so React doesn't try to render a second `<head>` mid-tree
 * (which throws hydration errors in the App Router). Auth check
 * matches the dashboard layout so unauthorized users still bounce.
 */

export async function generateMetadata({
  params,
}: {
  params: Promise<{ portSlug: string }>;
}): Promise<Metadata> {
  const { portSlug } = await params;
  return {
    manifest: `/${portSlug}/scan/manifest.webmanifest`,
    appleWebApp: {
      capable: true,
      title: 'PN Scanner',
      statusBarStyle: 'default',
    },
    other: {
      // Android/Chrome equivalent of the apple-* meta. metadata.appleWebApp
      // covers iOS only; this preserves the existing PWA hint for Chrome.
      'mobile-web-app-capable': 'yes',
    },
  };
}

export const viewport: Viewport = {
  themeColor: '#3a7bc8',
  width: 'device-width',
  initialScale: 1,
  viewportFit: 'cover',
};

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) notFound();

  // Membership gate (mirrors the dashboard layout): super admins reach
  // every port; everyone else needs an explicit user_port_roles row for
  // THIS port. Without this the scanner resolved the port by slug alone,
  // so any authenticated user could scan receipts into a port they have
  // no role on.
  const profile = await db.query.userProfiles.findFirst({
    where: eq(userProfiles.userId, session.user.id),
  });
  if (!profile?.isSuperAdmin) {
    const membership = await db.query.userPortRoles.findFirst({
      where: and(eq(userPortRoles.userId, session.user.id), eq(userPortRoles.portId, port.id)),
    });
    if (!membership) notFound();
  }

  return (
    <QueryProvider>
      <PortProvider ports={[port]} defaultPortId={port.id}>
        <div className="min-h-dvh bg-background">{children}</div>
      </PortProvider>
    </QueryProvider>
  );
}
