/**
 * 统一系统角色 code（ADMIN/EMPLOYEE/MANAGER/LEADER -> Administrator/Employee/Manager/Leader）
 * 如果新 code 已存在，迁移关联关系并删除旧角色。
 */
import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

const ROLE_MAPPINGS = [
  { legacyCode: 'ADMIN', targetCode: 'Administrator', targetName: 'Administrator' },
  { legacyCode: 'MANAGER', targetCode: 'Manager', targetName: 'Manager' },
  { legacyCode: 'LEADER', targetCode: 'Leader', targetName: 'Leader' },
  { legacyCode: 'EMPLOYEE', targetCode: 'Employee', targetName: 'Employee' },
];

async function migrateRoleCode(legacyCode: string, targetCode: string, targetName: string) {
  await prisma.$transaction(async (tx) => {
    const legacyRole = await tx.role.findUnique({ where: { code: legacyCode } });
    if (!legacyRole) {
      console.log(`ℹ️  Skip ${legacyCode}: not found`);
      return;
    }

    const targetRole = await tx.role.findUnique({ where: { code: targetCode } });
    if (!targetRole) {
      await tx.role.update({
        where: { id: legacyRole.id },
        data: { code: targetCode, name: targetName },
      });
      console.log(`✅ Updated role code ${legacyCode} -> ${targetCode}`);
      return;
    }

    if (targetRole.id === legacyRole.id) {
      console.log(`ℹ️  Skip ${legacyCode}: already normalized`);
      return;
    }

    const legacyPermissions = await tx.rolePermission.findMany({
      where: { roleId: legacyRole.id },
      select: { permissionId: true },
    });

    for (const permission of legacyPermissions) {
      await tx.rolePermission.upsert({
        where: {
          roleId_permissionId: {
            roleId: targetRole.id,
            permissionId: permission.permissionId,
          },
        },
        update: {},
        create: {
          roleId: targetRole.id,
          permissionId: permission.permissionId,
        },
      });
    }

    await tx.rolePermission.deleteMany({ where: { roleId: legacyRole.id } });

    const legacyUserRoles = await tx.userRole.findMany({
      where: { roleId: legacyRole.id },
      select: { id: true, userId: true, organizationId: true },
    });

    for (const userRole of legacyUserRoles) {
      const exists = await tx.userRole.findFirst({
        where: {
          userId: userRole.userId,
          roleId: targetRole.id,
          organizationId: userRole.organizationId,
        },
        select: { id: true },
      });

      if (exists) {
        await tx.userRole.delete({ where: { id: userRole.id } });
      } else {
        await tx.userRole.update({
          where: { id: userRole.id },
          data: { roleId: targetRole.id },
        });
      }
    }

    await tx.role.delete({ where: { id: legacyRole.id } });
    console.log(`✅ Merged role ${legacyCode} -> ${targetCode}`);
  });
}

async function main() {
  console.log('🔧 Migrating system role codes...');
  for (const mapping of ROLE_MAPPINGS) {
    await migrateRoleCode(mapping.legacyCode, mapping.targetCode, mapping.targetName);
  }
  console.log('✅ Role code migration completed');
}

main()
  .catch((error) => {
    console.error('❌ Role code migration failed:', error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
