import { Injectable, Logger } from '@nestjs/common';
import { Permission } from '@tria-plc/iamapi-common';
import { DataSource } from 'typeorm';

/** Renamed rule-engine resources: old key -> new key (same permission id). */
const PERMISSION_KEY_RENAMES: ReadonlyArray<{ from: string; to: string }> = [
  {
    from: 'edr_freight_app:rule_engine:priority_rules:view',
    to: 'edr_freight_app:rule_engine:priority_configs:view',
  },
  {
    from: 'edr_freight_app:rule_engine:priority_rules:manage',
    to: 'edr_freight_app:rule_engine:priority_configs:manage',
  },
];

@Injectable()
export class FreightPermissionKeyMigrationSeeder {
  private readonly logger = new Logger(FreightPermissionKeyMigrationSeeder.name);

  constructor(private readonly dataSource: DataSource) {}

  async run() {
    const permissionRepository = this.dataSource.getRepository(Permission);

    for (const { from, to } of PERMISSION_KEY_RENAMES) {
      const existing = await permissionRepository.findOne({
        where: { key: from },
        select: { id: true, key: true },
      });

      if (!existing) {
        continue;
      }

      const targetExists = await permissionRepository.existsBy({ key: to });
      if (targetExists) {
        this.logger.warn(
          `Skipping permission key rename ${from} -> ${to}: target key already exists`,
        );
        continue;
      }

      await permissionRepository.update({ id: existing.id }, { key: to });
      this.logger.log(`Renamed permission key ${from} -> ${to}`);
    }
  }
}
