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

import { withAuth, withPermission } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { bulkHardDeleteClients } 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),
  code: z.string().regex(/^\d{4}$/, '4-digit code required'),
  typedPhrase: z.string().min(1, 'Type the confirmation phrase'),
});

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