import { NextResponse } from 'next/server';
import { z } from 'zod';

import { withAuth, withPermission, withRateLimit } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { requestBulkHardDeleteCode } from '@/lib/services/client-hard-delete.service';
import { errorResponse } from '@/lib/errors';

const bodySchema = z.object({
  ids: z.array(z.string().min(1)).min(1).max(100),
});

export const POST = withAuth(
  withPermission(
    'admin',
    'permanently_delete_clients',
    withRateLimit('hardDeleteCode', async (req, ctx) => {
      try {
        const { ids } = await parseBody(req, bodySchema);
        const result = await requestBulkHardDeleteCode({
          clientIds: ids,
          portId: ctx.portId,
          requesterUserId: ctx.userId,
          meta: {
            userId: ctx.userId,
            portId: ctx.portId,
            ipAddress: ctx.ipAddress,
            userAgent: ctx.userAgent,
          },
        });
        return NextResponse.json({ data: result });
      } catch (error) {
        return errorResponse(error);
      }
    }),
  ),
);
