import { NextResponse } from 'next/server';

import { withPortalAuth } from '@/lib/portal/helpers';
import { getDocumentDownloadUrl } from '@/lib/services/portal.service';
import { logger } from '@/lib/logger';

export const GET = withPortalAuth(async (_req, session, params) => {
  try {
    const documentId = params.documentId;

    if (!documentId) {
      return NextResponse.json({ error: 'Document ID required' }, { status: 400 });
    }

    const url = await getDocumentDownloadUrl(session.clientId, documentId, session.portId);

    if (!url) {
      return NextResponse.json({ error: 'Document not found' }, { status: 404 });
    }

    return NextResponse.json({ url });
  } catch (error) {
    logger.error({ error }, 'Portal document download URL fetch failed');
    return NextResponse.json({ error: 'Failed to generate download URL' }, { status: 500 });
  }
});
