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

import { db } from '@/lib/db';
import { files } from '@/lib/db/schema/documents';
import { getStorageBackend } from '@/lib/storage';
import { errorResponse, NotFoundError } from '@/lib/errors';

/**
 * Public, unauthenticated stream-by-id for branding assets only. Used by
 * outbound email templates and the branded auth shell - surfaces where
 * the consumer can't authenticate (an inbox image fetch has no session
 * cookie). The `category = 'branding'` gate ensures only assets the
 * admin explicitly uploaded as port branding leak through this surface;
 * every other category (eoi, contract, receipt, …) keeps its
 * authenticated `/api/v1/files/[id]/preview` path.
 *
 * Cached for a day at the edge. Admins replacing a logo write a new
 * file id (the system_settings URL changes), so a stale CDN entry for
 * the old id is harmless.
 */
export async function GET(_req: NextRequest, ctx: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await ctx.params;
    const row = await db.query.files.findFirst({ where: eq(files.id, id) });
    if (!row || row.category !== 'branding') {
      throw new NotFoundError('File');
    }

    const backend = await getStorageBackend();
    const stream = await backend.get(row.storagePath);

    // Convert the Node Readable into a Web ReadableStream so NextResponse
    // can hand it back without buffering the whole blob in memory.
    const webStream = new ReadableStream<Uint8Array>({
      start(controller) {
        stream.on('data', (chunk: Buffer) => controller.enqueue(new Uint8Array(chunk)));
        stream.on('end', () => controller.close());
        stream.on('error', (err) => controller.error(err));
      },
    });

    return new NextResponse(webStream, {
      headers: {
        'Content-Type': row.mimeType ?? 'application/octet-stream',
        'Cache-Control': 'public, max-age=86400, immutable',
      },
    });
  } catch (error) {
    return errorResponse(error);
  }
}
