import { NextResponse } from 'next/server';
import { prisma } from '../../../../lib/prisma';

export async function GET(_req: Request, { params }: { params: { id: string } }) {
  const image = await prisma.listingImage.findUnique({
    where: { id: params.id },
    select: { data: true, mimeType: true, url: true, updatedAt: true },
  });

  if (!image) {
    return NextResponse.json({ error: 'Not found' }, { status: 404 });
  }

  if (image.data) {
    const res = new NextResponse(image.data, {
      status: 200,
      headers: {
        'Content-Type': image.mimeType || 'application/octet-stream',
        'Cache-Control': 'public, max-age=86400',
      },
    });
    if (image.updatedAt) {
      res.headers.set('Last-Modified', image.updatedAt.toUTCString());
    }
    return res;
  }

  if (image.url) {
    return NextResponse.redirect(image.url, { status: 302 });
  }

  return NextResponse.json({ error: 'Image missing' }, { status: 404 });
}
