import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { getPreviewUrl } from '@/lib/services/files';

export const GET = withAuth(
  withPermission('files', 'view', async (req, ctx, params) => {
    try {
      const result = await getPreviewUrl(params.id!, ctx.portId);
      // `?redirect=1` → 302 to the presigned (inline) URL so a plain
      // <a href>/<Link> opens the file in the browser. Default returns the
      // JSON envelope for programmatic consumers (e.g. FilePreviewDialog).
      if (new URL(req.url).searchParams.has('redirect')) {
        return NextResponse.redirect(result.url, 302);
      }
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
