import { NextResponse } from 'next/server';
import { eq } from 'drizzle-orm';

import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema/ports';

/**
 * Per-port PWA manifest. Scoped to `/<portSlug>/scan` so the install
 * only covers the scanner page, not the rest of the CRM. Each port
 * gets its own homescreen icon labeled with its name.
 */
export async function GET(_req: Request, { params }: { params: Promise<{ portSlug: string }> }) {
  const { portSlug } = await params;
  const port = await db.query.ports.findFirst({ where: eq(ports.slug, portSlug) });
  const portName = port?.name ?? 'CRM';

  const manifest = {
    name: `${portName} - Scanner`,
    short_name: 'Scanner',
    description: `Capture and submit expense receipts for ${portName}.`,
    start_url: `/${portSlug}/scan`,
    scope: `/${portSlug}/scan`,
    display: 'standalone',
    orientation: 'portrait',
    background_color: '#ffffff',
    theme_color: '#3a7bc8',
    icons: [
      { src: '/icon-192.png', sizes: '192x192', type: 'image/png' },
      { src: '/icon-512.png', sizes: '512x512', type: 'image/png' },
      {
        src: '/icon-512-maskable.png',
        sizes: '512x512',
        type: 'image/png',
        purpose: 'maskable',
      },
    ],
  };

  return NextResponse.json(manifest, {
    headers: {
      'Content-Type': 'application/manifest+json',
      'Cache-Control': 'public, max-age=300, must-revalidate',
    },
  });
}
