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 { updateQualificationCriterionSchema } from '@/lib/validators/qualification';
import { deleteCriterion, updateCriterion } from '@/lib/services/qualification.service';

export const PATCH = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx, params) => {
    try {
      const body = await parseBody(req, updateQualificationCriterionSchema);
      const row = await updateCriterion(params.id!, ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: row });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const DELETE = withAuth(
  withPermission('admin', 'manage_settings', async (_req, ctx, params) => {
    try {
      await deleteCriterion(params.id!, ctx.portId, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return new NextResponse(null, { status: 204 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
