import type { EntityManager } from '@mikro-orm/core';
import { Role } from '../modules/roles/entities/role.entity';
import type { Permission } from '../common/enums/permission.enum';
import type { Permission as PermissionEntity } from '../modules/roles/entities/permission.entity';
import { rolesData } from './data/roles.data';

export class RolesSeeder {
  async run(em: EntityManager, permissions: PermissionEntity[]): Promise<Map<string, Role>> {
    const rolesMap = new Map<string, Role>();

    for (const roleConfig of rolesData) {
      let role = await em.findOne(Role, { name: roleConfig.name });
      if (!role) {
        role = em.create(Role, {
          name: roleConfig.name,
          isSystem: true,
        });

        // Add permissions based on role configuration
        // TypeScript knows role is not null here because we just created it
        const newRole = role;
        // Use the permission filter for all roles
        const filteredPermissions = permissions.filter(p => roleConfig.permissionFilter(p.name as Permission));
        filteredPermissions.forEach(p => newRole.permissions.add(p));

        em.persist(newRole);
      }
      // Always add to map, whether existing or newly created
      rolesMap.set(roleConfig.name, role);
    }

    await em.flush();
    return rolesMap;
  }
}
