import type { FastifyInstance } from 'fastify';
import type { SecretMigrateService } from '../services/secret-migrate.service.js';

export function registerSecretMigrateRoutes(
  app: FastifyInstance,
  service: SecretMigrateService,
): void {
  /**
   * POST /api/v1/secrets/migrate
   *   body: { from: string, to: string, names?: string[], keepSource?: boolean, dryRun?: boolean }
   *   RBAC: operation `migrate-secrets` (role:run).
   */
  app.post<{
    Body: {
      from: string;
      to: string;
      names?: string[];
      keepSource?: boolean;
      dryRun?: boolean;
    };
  }>('/api/v1/secrets/migrate', async (request, reply) => {
    const { from, to, names, keepSource, dryRun } = request.body;
    if (!from || !to) {
      reply.code(400);
      return { error: 'from and to are required' };
    }

    if (dryRun === true) {
      const options: Parameters<SecretMigrateService['dryRun']>[0] = { from, to };
      if (names !== undefined) options.names = names;
      if (keepSource !== undefined) options.keepSource = keepSource;
      const secrets = await service.dryRun(options);
      return { dryRun: true, candidates: secrets.map((s) => ({ id: s.id, name: s.name })) };
    }

    const options: Parameters<SecretMigrateService['migrate']>[0] = { from, to };
    if (names !== undefined) options.names = names;
    if (keepSource !== undefined) options.keepSource = keepSource;
    return service.migrate(options);
  });
}
