/**
 * Admin-triggered storage migration. Same code path as `scripts/migrate-storage.ts`
 * (both delegate to `runMigration()` in `@/lib/storage/migrate`). Body:
 *   { from: 's3'|'filesystem', to: 's3'|'filesystem', dryRun?: boolean }
 *
 * Super-admin only. The `/[portSlug]/admin` segment is already gated; this
 * route enforces the same constraint defensively.
 */

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

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { runMigration } from '@/lib/storage/migrate';

const schema = z.object({
  from: z.enum(['s3', 'filesystem']),
  to: z.enum(['s3', 'filesystem']),
  dryRun: z.boolean().default(false),
  skipMigration: z.boolean().optional(),
});

export const runtime = 'nodejs';

export const POST = withAuth(async (req, ctx) => {
  try {
    requireSuperAdmin(ctx, 'admin.storage.migrate');
    const body = await parseBody(req, schema);
    if (body.from === body.to) {
      throw new ValidationError('from and to must differ');
    }
    const result = await runMigration({ ...body, userId: ctx.userId });
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
