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

const prisma = new PrismaClient();

async function main() {
  console.log('Adding developer:access permission...');

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

  console.log('Permission created/found:', developerPerm);

  // Get the Admin role
  const adminRole = await prisma.role.findUnique({
    where: { name: 'Admin' },
    include: { permissions: true },
  });

  if (!adminRole) {
    console.log('Admin role not found!');
    return;
  }

  // Check if Admin already has this permission
  const hasPermission = adminRole.permissions.some(
    (rp) => rp.permissionId === developerPerm.id
  );

  if (!hasPermission) {
    await prisma.rolePermission.create({
      data: {
        roleId: adminRole.id,
        permissionId: developerPerm.id,
      },
    });
    console.log('Added developer:access permission to Admin role');
  } else {
    console.log('Admin role already has developer:access permission');
  }

  console.log('Done!');
}

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