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

const prisma = new PrismaClient();

async function main() {
  // Create settings permissions
  const settingsPermissions = [
    { resource: 'settings', action: 'read' },
    { resource: 'settings', action: 'update' },
  ];

  for (const perm of settingsPermissions) {
    await prisma.permission.upsert({
      where: {
        resource_action: {
          resource: perm.resource,
          action: perm.action,
        },
      },
      update: {},
      create: perm,
    });
  }

  console.log('Settings permissions created');

  // Add to Admin role
  const adminRole = await prisma.role.findUnique({
    where: { name: 'Admin' },
  });

  if (adminRole) {
    const newPermissions = await prisma.permission.findMany({
      where: { resource: 'settings' },
    });

    for (const perm of newPermissions) {
      await prisma.rolePermission.upsert({
        where: {
          roleId_permissionId: {
            roleId: adminRole.id,
            permissionId: perm.id,
          },
        },
        update: {},
        create: {
          roleId: adminRole.id,
          permissionId: perm.id,
        },
      });
    }

    console.log('Settings permissions added to Admin role');
  }
}

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