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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { ports } from '@/lib/db/schema/ports';
import { errorResponse, ValidationError } from '@/lib/errors';
import { resolvePortLogo } from '@/lib/pdf/brand-kit/logo';
import { renderPdf } from '@/lib/pdf/render';
import { BrandingSamplePdf } from '@/lib/pdf/templates/branding-sample';

/**
 * GET /api/v1/admin/branding/logo/sample-pdf
 *
 * Renders a one-page PDF that exercises the brand-kit header, footer, and a
 * couple of tables/charts. Used by the admin Branding UI's "Test with sample
 * PDF" button so the admin can preview their logo in the actual report shell
 * before generating real reports.
 */
export const GET = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx) => {
    try {
      if (!ctx.portId) throw new ValidationError('No active port');
      const port = await db.query.ports.findFirst({ where: eq(ports.id, ctx.portId) });
      if (!port) throw new ValidationError('Unknown port');
      const logo = await resolvePortLogo(port.id);
      const bytes = await renderPdf(
        <BrandingSamplePdf portName={port.name} logoBuffer={logo.buffer} />,
      );
      return new NextResponse(new Uint8Array(bytes), {
        status: 200,
        headers: {
          'content-type': 'application/pdf',
          'content-disposition': 'inline; filename="branding-sample.pdf"',
          'cache-control': 'no-store',
        },
      });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
