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

export class PermissionSeeder {
    constructor(private prisma: PrismaClient) { }

    async run(): Promise<void> {
      console.log('Seeding permissions...');

      // Delete existing permissions to avoid duplicates
      await this.prisma.permissions.deleteMany({});

      try {
        // Fetch all resources and roles
        const allResources = await this.prisma.resources.findMany();
        const adminRole = await this.prisma.roles.findUnique({
          where: { name: 'admin' },
        });
        const viewerRole = await this.prisma.roles.findUnique({
          where: { name: 'viewer' },
        });
        const staffRole = await this.prisma.roles.findUnique({
          where: { name: 'staff' },
        });

        if (!adminRole || !viewerRole || !staffRole) {
          console.error('Roles not found. Please seed roles first.');
          return;
        }

        // Admin permissions - full access to all resources
        for (const resource of allResources) {
          await this.createPermissions(adminRole.id, resource.id, [
            'create',
            'read',
            'update',
            'delete',
          ]);
        }

        // Viewer permissions - read-only access to all resources
        for (const resource of allResources) {
          await this.createPermissions(viewerRole.id, resource.id, ['read']);
        }

        // Staff permissions - mixed permissions based on resource
        for (const resource of allResources) {
          if (
            ['roles', 'permissions', 'resources', 'users'].includes(
              resource.name
            )
          ) {
            // Staff can only read roles, permissions, resources, and users
            await this.createPermissions(staffRole.id, resource.id, ['read']);
          } else {
            // Staff can create, read, update but not delete other resources
            await this.createPermissions(staffRole.id, resource.id, [
              'create',
              'read',
              'update',
            ]);
          }
        }

        console.log('Permissions seeded successfully!');
      } catch (error) {
        console.error('Error seeding permissions:', error);
      }
    }

    private async createPermissions(roleId: string, resourceId: string, actions: string[]) {
        for (const action of actions) {
            try {
                const permission = await this.prisma.permissions.createMany({
                    data: {
                        action: action,
                        resource_id: resourceId,
                        role_id: roleId,
                    },
                    skipDuplicates: true, // Skip if the permission already exists
                });


                console.log(`Created permission: ${action} for role ${roleId} on resource ${resourceId}`);

            } catch (error) {
                console.error(`Error creating permission for role ${roleId} on resource ${resourceId}:`, error);
            }
        }
    }
}