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 { createQualificationCriterionSchema } from '@/lib/validators/qualification';
import { createCriterion, listCriteriaForPort } from '@/lib/services/qualification.service';

export const GET = withAuth(async (_req, ctx) => {
  try {
    const data = await listCriteriaForPort(ctx.portId);
    return NextResponse.json({ data });
  } catch (error) {
    return errorResponse(error);
  }
});

export const POST = withAuth(
  withPermission('admin', 'manage_settings', async (req, ctx) => {
    try {
      const body = await parseBody(req, createQualificationCriterionSchema);
      const row = await createCriterion(ctx.portId, body, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });
      return NextResponse.json({ data: row }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
