import { NextRequest, NextResponse } from 'next/server';

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { createFieldSchema } from '@/lib/validators/custom-fields';
import { listDefinitions, createDefinition } from '@/lib/services/custom-fields.service';

export const GET = withAuth(
  withPermission('admin', 'manage_custom_fields', async (req: NextRequest, ctx) => {
    try {
      const { searchParams } = new URL(req.url);
      const entityType = searchParams.get('entityType') ?? undefined;

      const data = await listDefinitions(ctx.portId, entityType);
      return NextResponse.json({ data });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);

export const POST = withAuth(
  withPermission('admin', 'manage_custom_fields', async (req: NextRequest, ctx) => {
    try {
      const data = await parseBody(req, createFieldSchema);

      const definition = await createDefinition(ctx.portId, ctx.userId, data, {
        userId: ctx.userId,
        portId: ctx.portId,
        ipAddress: ctx.ipAddress,
        userAgent: ctx.userAgent,
      });

      return NextResponse.json({ data: definition }, { status: 201 });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
