import { NextResponse } from 'next/server';

import { errorResponse, NotFoundError, ValidationError } from '@/lib/errors';
import { logger } from '@/lib/logger';
import { withPortalAuth } from '@/lib/portal/helpers';
import { getDocumentDownloadUrl } from '@/lib/services/portal.service';

export const GET = withPortalAuth(async (_req, session, params) => {
  try {
    const documentId = params.documentId;
    if (!documentId) throw new ValidationError('documentId is required');

    const url = await getDocumentDownloadUrl(session.clientId, documentId, session.portId);
    if (!url) throw new NotFoundError('document');

    return NextResponse.json({ url });
  } catch (error) {
    logger.error({ err: error }, 'Portal document download URL fetch failed');
    return errorResponse(error);
  }
});
