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

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

const hardDeleteSchema = z.object({
  code: z.string().regex(/^\d{4}$/, '4-digit code required'),
  typedName: z.string().min(1, 'Type the client name to confirm'),
});

/**
 * Permanently delete an archived client. Gated on the dedicated
 * `admin.permanently_delete_clients` permission AND requires both:
 *   - the 4-digit code that was emailed to the operator (10 min TTL),
 *   - the typed full name of the client (case-insensitive equality).
 * The service additionally enforces that the client is already archived.
 */
export const POST = withAuth(
  withPermission('admin', 'permanently_delete_clients', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('client');
      const body = await parseBody(req, hardDeleteSchema);

      const result = await hardDeleteClient({
        clientId: id,
        portId: ctx.portId,
        requesterUserId: ctx.userId,
        code: body.code,
        typedName: body.typedName,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });

      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
