import { NextResponse } from 'next/server';

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

/**
 * Send a one-time confirmation code to the operator's account email so
 * they can permanently delete an archived client. Two-permission gate:
 * `clients.delete` (the standard archive permission) is enforced by the
 * route wrapper; the service additionally requires the client to be
 * archived. The dedicated `admin.permanently_delete_clients` flag is
 * checked by the partner /hard-delete route - see route comment there.
 */
export const POST = withAuth(
  withPermission(
    'admin',
    'permanently_delete_clients',
    withRateLimit('hardDeleteCode', async (_req, ctx, params) => {
      try {
        const id = params.id;
        if (!id) throw new NotFoundError('client');

        const result = await requestHardDeleteCode({
          clientId: id,
          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);
      }
    }),
  ),
);
