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

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

/**
 * Smart restore endpoint. Replaces the previous dumb-restore which just
 * cleared archived_at. The new flow consults the archive_metadata
 * persisted at archive time and applies the operator's reversal
 * selections.
 *
 * Backwards-compat: clients archived before the smart-archive feature
 * have no archive_metadata. The dossier returns empty arrays in that
 * case, and a POST with no body simply un-archives them - same effect
 * as the old endpoint.
 */
const restoreSchema = z.object({
  applyReversals: z.array(z.string().min(1)).default([]),
});

export const POST = withAuth(
  withPermission('clients', 'edit', async (req, ctx, params) => {
    try {
      const id = params.id;
      if (!id) throw new NotFoundError('client');

      // Tolerate an empty body for the legacy "just unarchive" call site.
      let body: { applyReversals: string[] } = { applyReversals: [] };
      try {
        body = await parseBody(req, restoreSchema);
      } catch {
        // Empty / non-JSON body - defaults are fine.
      }

      const result = await restoreClientWithSelections({
        clientId: id,
        portId: ctx.portId,
        selections: body,
        meta: {
          userId: ctx.userId,
          portId: ctx.portId,
          ipAddress: ctx.ipAddress,
          userAgent: ctx.userAgent,
        },
      });
      return NextResponse.json({ data: result });
    } catch (error) {
      return errorResponse(error);
    }
  }),
);
