<?php

namespace Database\Seeders;

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

/**
 * Seeder: RModulePermissionSeeder
 * 
 * Seeds permissions for Research, Advocacy, and Partnership modules.
 * Assigns permissions to appropriate roles.
 * 
 * @author SSHIA Development Team
 * @version 1.0.0
 */
class RModulePermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Clear cache
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        // Create permissions for each module
        $permissions = $this->createPermissions();

        // Assign permissions to roles
        $this->assignPermissionsToRoles($permissions);

        $this->command->info('Module permissions seeded successfully!');

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

    /**
     * Create all permissions.
     */
    protected function createPermissions(): array
    {
        $permissions = [];

        // ===========================================
        // Research & Innovation Centre Permissions
        // ===========================================
        $researchPermissions = [
            // View permissions
            'view publications',
            'view own publications',
            'view featured publications',
            
            // Create/Edit permissions
            'create publications',
            'edit publications',
            'edit own publications',
            'delete publications',
            'delete own publications',
            
            // Submission permissions
            'submit publications',
            'resubmit publications',
            
            // Review permissions
            'review publications',
            'approve publications',
            'reject publications',
            'request revision',
            
            // Featured permissions
            'feature publications',
            
            // File permissions
            'upload publication files',
            'download publication files',
            
            // Admin permissions
            'manage publications',
            'view review history',
            'view review scores',
            'moderate publications',
        ];

        foreach ($researchPermissions as $permission) {
            $permissions['research'][] = Permission::firstOrCreate([
                'name' => $permission,
                'guard_name' => 'web',
            ]);
        }

        // ===========================================
        // Digital Health Advocacy Permissions
        // ===========================================
        $advocacyPermissions = [
            // Campaign permissions
            'view campaigns',
            'create campaigns',
            'edit campaigns',
            'delete campaigns',
            'manage campaigns',
            'feature campaigns',
            
            // Story permissions
            'view stories',
            'create stories',
            'edit stories',
            'edit own stories',
            'delete stories',
            'delete own stories',
            'moderate stories',
            'approve stories',
            'reject stories',
            'feature stories',
            
            // Poll permissions
            'view polls',
            'create polls',
            'edit polls',
            'delete polls',
            'manage polls',
            'view poll results',
            'close polls',
            
            // Analytics permissions
            'view advocacy analytics',
            'export advocacy reports',
        ];

        foreach ($advocacyPermissions as $permission) {
            $permissions['advocacy'][] = Permission::firstOrCreate([
                'name' => $permission,
                'guard_name' => 'web',
            ]);
        }

        // ===========================================
        // Partnership & Collaboration Permissions
        // ===========================================
        $partnershipPermissions = [
            // Partner permissions
            'view partners',
            'view own partners',
            'create partners',
            'edit partners',
            'edit own partners',
            'delete partners',
            'manage partners',
            'verify partners',
            'feature partners',
            
            // Partnership (MOU) permissions
            'view partnerships',
            'create partnerships',
            'edit partnerships',
            'delete partnerships',
            'manage partnerships',
            'renew partnerships',
            'terminate partnerships',
            'download partnership documents',
            
            // Forum permissions
            'view forum',
            'create forum threads',
            'edit forum threads',
            'edit own forum threads',
            'delete forum threads',
            'delete own forum threads',
            'reply to forum threads',
            'moderate forum',
            'pin forum threads',
            'lock forum threads',
            
            // Contact permissions
            'view partner contacts',
            'manage partner contacts',
        ];

        foreach ($partnershipPermissions as $permission) {
            $permissions['partnership'][] = Permission::firstOrCreate([
                'name' => $permission,
                'guard_name' => 'web',
            ]);
        }

        return $permissions;
    }

    /**
     * Assign permissions to roles.
     */
    protected function assignPermissionsToRoles(array $permissions): void
    {
        // Get roles
        $superManager = Role::where('name', 'Super Manager')->first();
        $manager = Role::where('name', 'Manager')->first();
        $healthMarketer = Role::where('name', 'Health Marketor')->first();
        $contributor = Role::where('name', 'Contributor')->first();
        $partner = Role::where('name', 'Partners')->first();
        $mentor = Role::where('name', 'Mentor')->first();
        $trainer = Role::where('name', 'Trainers')->first();
        $member = Role::where('name', 'Members')->first();

        // ===========================================
        // Super Manager - Full access
        // ===========================================
        if ($superManager) {
            // Give all R-module permissions (additive — do not sync/overwrite)
            $allRModulePermissions = array_merge(
                array_map(fn($p) => $p->name, $permissions['research'] ?? []),
                array_map(fn($p) => $p->name, $permissions['advocacy'] ?? []),
                array_map(fn($p) => $p->name, $permissions['partnership'] ?? [])
            );
            $superManager->givePermissionTo($allRModulePermissions);
        }

        // ===========================================
        // Manager - Moderation and management
        // ===========================================
        if ($manager) {
            $managerPermissions = [
                // Research
                'view publications',
                'view own publications',
                'view featured publications',
                'review publications',
                'approve publications',
                'reject publications',
                'request revision',
                'feature publications',
                'download publication files',
                'view review history',
                'view review scores',
                'moderate publications',
                
                // Advocacy
                'view campaigns',
                'edit campaigns',
                'manage campaigns',
                'feature campaigns',
                'view stories',
                'moderate stories',
                'approve stories',
                'reject stories',
                'feature stories',
                'view polls',
                'edit polls',
                'manage polls',
                'view poll results',
                'close polls',
                'view advocacy analytics',
                
                // Partnership
                'view partners',
                'edit partners',
                'manage partners',
                'verify partners',
                'feature partners',
                'view partnerships',
                'edit partnerships',
                'manage partnerships',
                'renew partnerships',
                'view forum',
                'moderate forum',
                'pin forum threads',
                'lock forum threads',
            ];
            $manager->givePermissionTo($managerPermissions);
        }

        // ===========================================
        // Health Marketer - Campaign and poll management
        // ===========================================
        if ($healthMarketer) {
            $marketerPermissions = [
                // Research (limited)
                'view publications',
                'view featured publications',
                
                // Advocacy (full access)
                'view campaigns',
                'create campaigns',
                'edit campaigns',
                'manage campaigns',
                'feature campaigns',
                'view stories',
                'create stories',
                'edit stories',
                'moderate stories',
                'approve stories',
                'reject stories',
                'feature stories',
                'view polls',
                'create polls',
                'edit polls',
                'delete polls',
                'manage polls',
                'view poll results',
                'close polls',
                'view advocacy analytics',
                'export advocacy reports',
                
                // Partnership (limited)
                'view partners',
                'view partnerships',
            ];
            $healthMarketer->givePermissionTo($marketerPermissions);
        }

        // ===========================================
        // Contributor - Research submission
        // ===========================================
        if ($contributor) {
            $contributorPermissions = [
                // Research
                'view publications',
                'view own publications',
                'view featured publications',
                'create publications',
                'edit own publications',
                'delete own publications',
                'submit publications',
                'resubmit publications',
                'upload publication files',
                'download publication files',
                
                // Advocacy (limited)
                'view campaigns',
                'view stories',
                'create stories',
                'edit own stories',
                'delete own stories',
                'view polls',
                'view poll results',
                
                // Partnership (limited)
                'view partners',
                'view forum',
            ];
            $contributor->givePermissionTo($contributorPermissions);
        }

        // ===========================================
        // Partner - Partner profile and forum
        // ===========================================
        if ($partner) {
            $partnerPermissions = [
                // Research (limited)
                'view publications',
                'view featured publications',
                
                // Advocacy (limited)
                'view campaigns',
                'view stories',
                'create stories',
                'edit own stories',
                'view polls',
                'view poll results',
                
                // Partnership
                'view partners',
                'view own partners',
                'edit own partners',
                'view partnerships',
                'view partner contacts',
                'manage partner contacts',
                
                // Forum
                'view forum',
                'create forum threads',
                'edit own forum threads',
                'delete own forum threads',
                'reply to forum threads',
            ];
            $partner->givePermissionTo($partnerPermissions);
        }

        // ===========================================
        // Mentor - Review and guidance
        // ===========================================
        if ($mentor) {
            $mentorPermissions = [
                // Research
                'view publications',
                'view own publications',
                'view featured publications',
                'create publications',
                'edit own publications',
                'review publications',
                'download publication files',
                
                // Advocacy
                'view campaigns',
                'view stories',
                'create stories',
                'edit own stories',
                'view polls',
                'view poll results',
                
                // Partnership
                'view partners',
                'view partnerships',
                
                // Forum
                'view forum',
                'create forum threads',
                'edit own forum threads',
                'delete own forum threads',
                'reply to forum threads',
            ];
            $mentor->givePermissionTo($mentorPermissions);
        }

        // ===========================================
        // Trainer/Member - Basic access
        // ===========================================
        $memberPermissions = [
            // Research (limited)
            'view publications',
            'view featured publications',
            'create publications',
            'edit own publications',
            'delete own publications',
            'submit publications',
            'upload publication files',
            
            // Advocacy (limited)
            'view campaigns',
            'view stories',
            'create stories',
            'edit own stories',
            'delete own stories',
            'view polls',
            'view poll results',
            
            // Partnership (limited)
            'view partners',
        ];

        if ($trainer) {
            $trainer->givePermissionTo($memberPermissions);
        }

        if ($member) {
            $member->givePermissionTo($memberPermissions);
        }
    }
}
