<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class CleanupPermissions extends Command
{
    protected $signature = 'admin:cleanup-permissions';
    protected $description = 'Remove duplicate permissions and keep proper capitalization';

    public function handle()
    {
        $this->info('Starting permission cleanup...');
        
        // Define the correct permission names (Title Case)
        $correctPermissions = [
            // Dashboard permissions
            'Access Dashboard',
            
            // User management permissions
            'View Users',
            'Create User', 
            'Edit User',
            'Delete User',
            'Reset Password',
            'Assign User Role',
            
            // Role management permissions
            'View Roles',
            'Create Role',
            'Edit Role', 
            'Delete Role',
            'Assign Permission',
            
            // Folder management permissions
            'View Folder',
            'Create Folder',
            'Edit Folder',
            'Delete Folder',
            'Share Folder',
            'Manage Folder Permissions',
            'Access Shared Folders',
            'View Folder Contents',
            
            // File management permissions
            'Upload Files',
            'Download Files',
            'Delete Files',
            'View File Metadata',
            'Search Files',
            
            // Profile permissions
            'Edit Profile',
            'Delete Profile',
            
            // Workflow permissions
            'Create Workflows',
            'Edit Workflows',
            'Delete Workflows',
            'View Workflows',
            'Execute Workflows',
            
            // Report permissions
            'View Reports',
            'Create Reports',
            'Export Reports',
            
            // Administrative permissions
            'Access Admin Panel',
            'Manage System Settings',
            'View System Logs',
            'Backup System',
            'Restore System',
        ];

        $this->info('Current permissions: ' . Permission::count());
        
        // Get all current permissions
        $currentPermissions = Permission::all();
        
        // Track which permissions to keep
        $permissionsToKeep = [];
        $permissionsToDelete = [];
        
        foreach ($correctPermissions as $correctName) {
            // Find if this permission exists (case insensitive)
            $found = $currentPermissions->first(function($perm) use ($correctName) {
                return strtolower($perm->name) === strtolower($correctName);
            });
            
            if ($found) {
                if ($found->name === $correctName) {
                    // Already correct, keep it
                    $permissionsToKeep[] = $found->id;
                    $this->line("✅ Keeping: {$found->name}");
                } else {
                    // Need to rename or find duplicates
                    $this->line("🔄 Found: {$found->name} -> Will update to: {$correctName}");
                    
                    // Check if correct version already exists
                    $correctExists = $currentPermissions->firstWhere('name', $correctName);
                    if ($correctExists) {
                        // Correct version exists, delete the incorrect one
                        $permissionsToDelete[] = $found->id;
                        $permissionsToKeep[] = $correctExists->id;
                        $this->line("❌ Deleting duplicate: {$found->name}");
                    } else {
                        // Update the incorrect one to correct name
                        $found->update(['name' => $correctName]);
                        $permissionsToKeep[] = $found->id;
                        $this->line("✅ Updated: {$found->name} -> {$correctName}");
                    }
                }
            } else {
                // Permission doesn't exist, create it
                $newPerm = Permission::create(['name' => $correctName]);
                $permissionsToKeep[] = $newPerm->id;
                $this->line("➕ Created: {$correctName}");
            }
        }
        
        // Delete duplicate/incorrect permissions
        if (!empty($permissionsToDelete)) {
            $this->info('Deleting duplicate permissions...');
            Permission::whereIn('id', $permissionsToDelete)->delete();
        }
        
        // Get all roles and reassign permissions
        $this->info('Updating role permissions...');
        $roles = Role::all();
        
        foreach ($roles as $role) {
            if ($role->name === 'Super Admin') {
                // Super Admin gets all permissions
                $role->syncPermissions(Permission::all());
                $this->line("✅ Super Admin: All permissions assigned");
            } elseif ($role->name === 'Manager') {
                // Manager gets most permissions except admin ones
                $managerPermissions = [
                    'Access Dashboard', 'View Users', 'Create User', 'Edit User',
                    'View Roles', 'View Folder', 'Create Folder', 'Edit Folder',
                    'Share Folder', 'Access Shared Folders', 'View Folder Contents',
                    'Upload Files', 'Download Files', 'View File Metadata', 'Search Files',
                    'Edit Profile', 'View Workflows', 'Create Workflows', 'Edit Workflows',
                    'View Reports', 'Create Reports'
                ];
                $permissions = Permission::whereIn('name', $managerPermissions)->get();
                $role->syncPermissions($permissions);
                $this->line("✅ Manager: {$permissions->count()} permissions assigned");
            } elseif ($role->name === 'User') {
                // User gets basic permissions
                $userPermissions = [
                    'Access Dashboard', 'Access Shared Folders', 'View Folder Contents',
                    'Upload Files', 'Download Files', 'View File Metadata', 'Search Files',
                    'Edit Profile', 'View Workflows', 'View Reports'
                ];
                $permissions = Permission::whereIn('name', $userPermissions)->get();
                $role->syncPermissions($permissions);
                $this->line("✅ User: {$permissions->count()} permissions assigned");
            }
        }
        
        $finalCount = Permission::count();
        $this->info("✅ Cleanup complete! Final permission count: {$finalCount}");
        
        return Command::SUCCESS;
    }
}