import { PrismaClient } from '@prisma/client';

const prisma = new PrismaClient();

async function main() {
  console.log('Adding/updating permissions and Developer role...');

  // 1. Create or get the emails:delete permission
  const emailsDeletePerm = await prisma.permission.upsert({
    where: { resource_action: { resource: 'emails', action: 'delete' } },
    update: {},
    create: { resource: 'emails', action: 'delete' },
  });
  console.log('emails:delete permission created/found');

  // 2. Create or get the developer:access permission
  const developerAccessPerm = await prisma.permission.upsert({
    where: { resource_action: { resource: 'developer', action: 'access' } },
    update: {},
    create: { resource: 'developer', action: 'access' },
  });
  console.log('developer:access permission created/found');

  // 3. Create Developer role if it doesn't exist
  let developerRole = await prisma.role.findUnique({
    where: { name: 'Developer' },
  });

  if (!developerRole) {
    // Get all permissions for Developer role
    const allPermissions = await prisma.permission.findMany();
    developerRole = await prisma.role.create({
      data: {
        name: 'Developer',
        description: 'Voller Zugriff inkl. Entwickler-Tools',
        permissions: {
          create: allPermissions.map(p => ({ permissionId: p.id })),
        },
      },
    });
    console.log('Developer role created with all permissions');
  }

  // 4. Add emails:delete to Admin and Developer
  const rolesToUpdate = [
    { name: 'Admin', permissions: [emailsDeletePerm] },
    { name: 'Developer', permissions: [emailsDeletePerm, developerAccessPerm] },
  ];

  for (const roleConfig of rolesToUpdate) {
    const role = await prisma.role.findUnique({
      where: { name: roleConfig.name },
      include: { permissions: true },
    });

    if (!role) {
      console.log(`${roleConfig.name} role not found, skipping...`);
      continue;
    }

    for (const perm of roleConfig.permissions) {
      const hasPermission = role.permissions.some(
        (rp) => rp.permissionId === perm.id
      );

      if (!hasPermission) {
        await prisma.rolePermission.create({
          data: {
            roleId: role.id,
            permissionId: perm.id,
          },
        });
        console.log(`Added ${perm.resource}:${perm.action} to ${roleConfig.name}`);
      }
    }
  }

  console.log('Done!');
}

main()
  .catch((e) => {
    console.error(e);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
  });
