import { NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { setInterestQualificationSchema } from '@/lib/validators/qualification';
import {
  isInterestFullyQualified,
  listInterestQualifications,
  setInterestQualification,
} from '@/lib/services/qualification.service';

export const GET = withAuth(
  withPermission('interests', 'view', async (_req, ctx, params) => {
    try {
      const interestId = params.id!;
      const [criteria, fullyQualified] = await Promise.all([
        listInterestQualifications(interestId, ctx.portId),
        isInterestFullyQualified(interestId, ctx.portId),
      ]);
      return NextResponse.json({ data: { criteria, fullyQualified } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const PUT = withAuth(
  withPermission('interests', 'edit', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, setInterestQualificationSchema);
      const criteria = await setInterestQualification(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      const fullyQualified = criteria.every((c) => c.confirmed);
      return NextResponse.json({ data: { criteria, fullyQualified } });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
