import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ForbiddenError } from '@/lib/errors';
import { changeInterestStage, STAGE_NOOP } from '@/lib/services/interests.service';
import { changeStageSchema } from '@/lib/validators/interests';

export const PATCH = withAuth(
  withPermission('interests', 'change_stage', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, changeStageSchema);
      // Override (skip the canTransitionStage table) requires a stricter
      // permission. Reason field validation lives in the service.
      if (body.override) {
        const allowed = ctx.isSuperAdmin || !!ctx.permissions?.interests?.override_stage;
        if (!allowed) {
          throw new ForbiddenError(
            'You do not have permission to override the stage transition rules.',
          );
        }
      }
      const interest = await changeInterestStage(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      // A19 / F27: same-stage write returns the sentinel - emit 204.
      if (interest === STAGE_NOOP) {
        return new NextResponse(null, { status: 204 });
      }
      return NextResponse.json({ data: interest });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
