<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;

/**
 * OrganizationPermissionSeeder
 *
 * Seeds all permissions for the Organization Configuration Module.
 * Permissions are assigned to Super Manager and Manager roles.
 *
 * Permission Naming Convention: {action} {resource}
 * - view: Read-only access
 * - create: Ability to create new records
 * - edit: Ability to modify existing records
 * - delete: Ability to remove records
 * - manage: Full management access
 * - assign: Special action for leadership assignments
 * - complete: Special action for election cycles
 * - export: Ability to export data
 */
class OrganizationPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Define all organization module permissions
        $permissions = [
            // Organization Details Permissions
            'view organizations' => 'View organization details and list',
            'create organizations' => 'Create new organization records',
            'edit organizations' => 'Edit existing organization details',
            'delete organizations' => 'Delete organization records',

            // Leadership Positions Permissions
            'view leadership positions' => 'View leadership positions and hierarchy',
            'create leadership positions' => 'Create new leadership positions',
            'edit leadership positions' => 'Edit existing leadership positions',
            'delete leadership positions' => 'Delete leadership positions',
            'assign leadership' => 'Assign users to leadership positions and end assignments',

            // Election Cycles Permissions
            'view election cycles' => 'View election cycle details and list',
            'create election cycles' => 'Create new election cycles',
            'edit election cycles' => 'Edit existing election cycles',
            'delete election cycles' => 'Delete election cycles',
            'complete election cycles' => 'Mark election cycles as completed',

            // Voting Procedures Permissions
            'view voting procedures' => 'View voting procedure details and list',
            'create voting procedures' => 'Create new voting procedures',
            'edit voting procedures' => 'Edit existing voting procedures',
            'delete voting procedures' => 'Delete voting procedures',

            // Leadership History Permissions
            'view leadership history' => 'View leadership history records',
            'add leadership achievements' => 'Add achievements to leadership history records',

            // Staff History Permissions
            'view staff history' => 'View staff employment records',
            'create staff history' => 'Create new staff records',
            'edit staff history' => 'Edit existing staff records',
            'delete staff history' => 'Delete staff records',
            'add staff achievements' => 'Add achievements to staff records',

            // Organogram Permissions
            'view organogram' => 'View organizational hierarchy chart',
            'export organogram' => 'Export organogram to PDF, PNG, SVG, or JSON',
        ];

        // Create all permissions
        foreach ($permissions as $name => $description) {
            Permission::firstOrCreate(
                ['name' => $name],
                ['guard_name' => 'web']
            );
        }

        $this->command->info('Organization module permissions created successfully.');

        // Get Super Manager and Manager roles
        $superManager = Role::where('name', 'Super Manager')->first();
        $manager = Role::where('name', 'Manager')->first();

        if (!$superManager || !$manager) {
            $this->command->warn('Super Manager or Manager role not found. Please run RolePermissionSeeder first.');
            return;
        }

        // Assign ALL permissions to Super Manager
        $superManager->givePermissionTo(array_keys($permissions));
        $this->command->info('All organization permissions assigned to Super Manager.');

        // Assign specific permissions to Manager
        $managerPermissions = [
            // Organization Details
            'view organizations',
            'create organizations',
            'edit organizations',

            // Leadership Positions
            'view leadership positions',
            'create leadership positions',
            'edit leadership positions',
            'assign leadership',

            // Election Cycles
            'view election cycles',
            'create election cycles',
            'edit election cycles',
            'complete election cycles',

            // Voting Procedures
            'view voting procedures',
            'create voting procedures',
            'edit voting procedures',

            // Leadership History
            'view leadership history',
            'add leadership achievements',

            // Staff History
            'view staff history',
            'create staff history',
            'edit staff history',
            'add staff achievements',

            // Organogram
            'view organogram',
            'export organogram',
        ];

        $manager->givePermissionTo($managerPermissions);
        $this->command->info('Manager permissions assigned successfully.');

        // Display summary
        $this->command->newLine();
        $this->command->info('=== Organization Permission Seeder Summary ===');
        $this->command->info('Total permissions created: ' . count($permissions));
        $this->command->info('Super Manager permissions: ' . count($permissions) . ' (all)');
        $this->command->info('Manager permissions: ' . count($managerPermissions));
        $this->command->newLine();

        // Display all permissions for reference
        $this->command->info('=== All Organization Permissions ===');
        foreach ($permissions as $name => $description) {
            $superAccess = in_array($name, array_keys($permissions)) ? '✓' : '✗';
            $managerAccess = in_array($name, $managerPermissions) ? '✓' : '✗';
            $this->command->line("{$name}");
            $this->command->line("  - {$description}");
            $this->command->line("  - Super Manager: {$superAccess} | Manager: {$managerAccess}");
        }

        // Clear permission cache after seeding
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();
    }

    /**
     * Get all organization module permissions.
     * Useful for other seeders or installation scripts.
     *
     * @return array
     */
    public static function getPermissions(): array
    {
        return [
            'view organizations',
            'create organizations',
            'edit organizations',
            'delete organizations',
            'view leadership positions',
            'create leadership positions',
            'edit leadership positions',
            'delete leadership positions',
            'assign leadership',
            'view election cycles',
            'create election cycles',
            'edit election cycles',
            'delete election cycles',
            'complete election cycles',
            'view voting procedures',
            'create voting procedures',
            'edit voting procedures',
            'delete voting procedures',
            'view leadership history',
            'add leadership achievements',
            'view staff history',
            'create staff history',
            'edit staff history',
            'delete staff history',
            'add staff achievements',
            'view organogram',
            'export organogram',
        ];
    }

    /**
     * Get permissions for Manager role.
     *
     * @return array
     */
    public static function getManagerPermissions(): array
    {
        return [
            'view organizations',
            'create organizations',
            'edit organizations',
            'view leadership positions',
            'create leadership positions',
            'edit leadership positions',
            'assign leadership',
            'view election cycles',
            'create election cycles',
            'edit election cycles',
            'complete election cycles',
            'view voting procedures',
            'create voting procedures',
            'edit voting procedures',
            'view leadership history',
            'add leadership achievements',
            'view staff history',
            'create staff history',
            'edit staff history',
            'add staff achievements',
            'view organogram',
            'export organogram',
        ];
    }

    /**
     * Get permissions for Super Manager role (all permissions).
     *
     * @return array
     */
    public static function getSuperManagerPermissions(): array
    {
        return self::getPermissions();
    }
}
