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

const prisma = new PrismaClient();

async function main() {
  console.log('Adding provider permissions...');

  // Create provider permissions
  const actions = ['create', 'read', 'update', 'delete'];

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

  console.log('Provider permissions created');

  // Get all provider permissions
  const providerPermissions = await prisma.permission.findMany({
    where: { resource: 'providers' },
  });

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

  if (adminRole) {
    // Add provider permissions to admin role if not already assigned
    for (const perm of providerPermissions) {
      const exists = adminRole.permissions.some(rp => rp.permissionId === perm.id);
      if (!exists) {
        await prisma.rolePermission.create({
          data: {
            roleId: adminRole.id,
            permissionId: perm.id,
          },
        });
        console.log(`Added providers:${perm.action} to Admin role`);
      }
    }
  }

  // Get employee role and add read permission
  const employeeRole = await prisma.role.findUnique({
    where: { name: 'Mitarbeiter' },
    include: { permissions: true },
  });

  const providerReadPerm = providerPermissions.find(p => p.action === 'read');

  if (employeeRole && providerReadPerm) {
    const exists = employeeRole.permissions.some(rp => rp.permissionId === providerReadPerm.id);
    if (!exists) {
      await prisma.rolePermission.create({
        data: {
          roleId: employeeRole.id,
          permissionId: providerReadPerm.id,
        },
      });
      console.log('Added providers:read to Mitarbeiter role');
    }
  }

  // Get read-only role and add read permission
  const readOnlyRole = await prisma.role.findUnique({
    where: { name: 'Mitarbeiter (Nur-Lesen)' },
    include: { permissions: true },
  });

  if (readOnlyRole && providerReadPerm) {
    const exists = readOnlyRole.permissions.some(rp => rp.permissionId === providerReadPerm.id);
    if (!exists) {
      await prisma.rolePermission.create({
        data: {
          roleId: readOnlyRole.id,
          permissionId: providerReadPerm.id,
        },
      });
      console.log('Added providers:read to Mitarbeiter (Nur-Lesen) role');
    }
  }

  // Get customer role and add read permission
  const customerRole = await prisma.role.findUnique({
    where: { name: 'Kunde' },
    include: { permissions: true },
  });

  if (customerRole && providerReadPerm) {
    const exists = customerRole.permissions.some(rp => rp.permissionId === providerReadPerm.id);
    if (!exists) {
      await prisma.rolePermission.create({
        data: {
          roleId: customerRole.id,
          permissionId: providerReadPerm.id,
        },
      });
      console.log('Added providers:read to Kunde role');
    }
  }

  console.log('Provider permissions setup completed!');
}

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