import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { buildEoiContext } from '@/lib/services/eoi-context';

/**
 * Returns the resolved `EoiContext` — the actual data that would be
 * auto-filled into the EOI document — for the given interest. Drives
 * the EOI generate dialog's pre-flight preview so a sales rep can see
 * (and correct) every value before sending the document for signing.
 *
 * No mutation; pure read of denormalized data the EOI builder already
 * computes server-side. Returns 404 if the interest is missing or in
 * another port (the buildEoiContext function throws NotFoundError).
 */
export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const context = await buildEoiContext(params.id!, ctx.portId);
      return NextResponse.json({ data: context });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
