import type { EntityManager } from '@mikro-orm/core';
import { Permission as PermissionEntity } from '../modules/roles/entities/permission.entity';
import { getPermissionsData } from './data/permissions.data';

export class PermissionsSeeder {
  async run(em: EntityManager): Promise<PermissionEntity[]> {
    const permissions = getPermissionsData();
    const createdPermissions: PermissionEntity[] = [];

    for (const permData of permissions) {
      let permission = await em.findOne(PermissionEntity, { name: permData.name });
      if (!permission) {
        permission = em.create(PermissionEntity, permData);
        em.persist(permission);
      } else {
        // Update existing permission's title if it changed
        if (permission.title !== permData.title) {
          permission.title = permData.title;
          em.persist(permission);
        }
      }
      createdPermissions.push(permission);
    }

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