import { NextResponse } from 'next/server';

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

export const GET = withAuth(
  withPermission('files', 'view', async (req, ctx, params) => {
    try {
      const result = await getDownloadUrl(params.id!, ctx.portId);
      // `?redirect=1` → 302 straight to the presigned (attachment) URL so a
      // plain <a href>/<Link> downloads the file. Without it we return the
      // JSON envelope for programmatic consumers (e.g. fetch + anchor click).
      // Linking the browser at the JSON form used to dump raw `{data:{url}}`.
      if (new URL(req.url).searchParams.has('redirect')) {
        return NextResponse.redirect(result.url, 302);
      }
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
