<?php

namespace App\Console\Commands;

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

class TestRolesPermissions extends Command
{
    protected $signature = 'test:roles-permissions';
    protected $description = 'Test the roles and permissions system';

    public function handle()
    {
        $this->info('🧪 Testing Roles and Permissions System...');
        $this->newLine();

        // Test 1: Check if roles exist
        $this->info('1. Testing Roles...');
        try {
            $expectedRoles = ['superadmin', 'admin', 'pr_officer', 'po_officer', 'igp_officer', 'qc_officer'];
            $existingRoles = Role::pluck('name')->toArray();

            $this->info("  ✓ Found " . count($existingRoles) . " roles: " . implode(', ', $existingRoles));

            foreach ($expectedRoles as $role) {
                if (in_array($role, $existingRoles)) {
                    $this->info("    ✓ Role '{$role}' exists");
                } else {
                    $this->error("    ✗ Role '{$role}' missing");
                }
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Role testing failed: ' . $e->getMessage());
            return 1;
        }

        // Test 2: Check if permissions exist
        $this->info('2. Testing Permissions...');
        try {
            $totalPermissions = Permission::count();
            $this->info("  ✓ Found {$totalPermissions} total permissions");

            // Check some key permissions
            $keyPermissions = [
                'view_dashboard',
                'manage_users',
                'manage_contacts',
                'manage_items',
                'manage_purchase_requests',
                'manage_purchase_orders',
                'manage_igps',
                'manage_qcs'
            ];

            foreach ($keyPermissions as $permission) {
                $perm = Permission::where('name', $permission)->first();
                if ($perm) {
                    $this->info("    ✓ Permission '{$permission}' exists");
                } else {
                    $this->error("    ✗ Permission '{$permission}' missing");
                }
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Permission testing failed: ' . $e->getMessage());
            return 1;
        }

        // Test 3: Check default users
        $this->info('3. Testing Default Users...');
        try {
            $superadmin = User::where('email', 'superadmin@novaerp.com')->first();
            $admin = User::where('email', 'admin@novaerp.com')->first();

            if ($superadmin) {
                $this->info("  ✓ Superadmin user exists: {$superadmin->name}");
                $roles = $superadmin->getRoleNames();
                $this->info("    Roles: " . implode(', ', $roles->toArray()));

                // Check if superadmin has all permissions
                $allPermissions = Permission::count();
                $userPermissions = $superadmin->getAllPermissions()->count();
                $this->info("    Permissions: {$userPermissions}/{$allPermissions}");
            } else {
                $this->error('  ✗ Superadmin user missing');
            }

            if ($admin) {
                $this->info("  ✓ Admin user exists: {$admin->name}");
                $roles = $admin->getRoleNames();
                $this->info("    Roles: " . implode(', ', $roles->toArray()));

                // Check admin permissions
                $userPermissions = $admin->getAllPermissions()->count();
                $this->info("    Permissions: {$userPermissions}");
            } else {
                $this->error('  ✗ Admin user missing');
            }
        } catch (\Exception $e) {
            $this->error('  ✗ User testing failed: ' . $e->getMessage());
            return 1;
        }

        // Test 4: Test role permissions
        $this->info('4. Testing Role Permissions...');
        try {
            $roles = Role::with('permissions')->get();

            foreach ($roles as $role) {
                $permissionCount = $role->permissions->count();
                $this->info("  ✓ Role '{$role->name}': {$permissionCount} permissions");

                // Show some key permissions for each role
                $keyPerms = $role->permissions->take(5)->pluck('name')->toArray();
                if (!empty($keyPerms)) {
                    $this->info("    Key permissions: " . implode(', ', $keyPerms));
                }
            }
        } catch (\Exception $e) {
            $this->error('  ✗ Role permissions testing failed: ' . $e->getMessage());
            return 1;
        }

        // Test 5: Test user role methods
        $this->info('5. Testing User Role Methods...');
        try {
            if ($superadmin) {
                $this->info("  ✓ Superadmin role methods:");
                $this->info("    - hasRole('superadmin'): " . ($superadmin->hasRole('superadmin') ? 'true' : 'false'));
                $this->info("    - isSuperadmin(): " . ($superadmin->isSuperadmin() ? 'true' : 'false'));
                $this->info("    - isAdmin(): " . ($superadmin->isAdmin() ? 'true' : 'false'));
                $this->info("    - isOfficer(): " . ($superadmin->isOfficer() ? 'true' : 'false'));
                $this->info("    - Primary Role: {$superadmin->primary_role}");
            }

            if ($admin) {
                $this->info("  ✓ Admin role methods:");
                $this->info("    - hasRole('admin'): " . ($admin->hasRole('admin') ? 'true' : 'false'));
                $this->info("    - isSuperadmin(): " . ($admin->isSuperadmin() ? 'true' : 'false'));
                $this->info("    - isAdmin(): " . ($admin->isAdmin() ? 'true' : 'false'));
                $this->info("    - isOfficer(): " . ($admin->isOfficer() ? 'true' : 'false'));
                $this->info("    - Primary Role: {$admin->primary_role}");
            }
        } catch (\Exception $e) {
            $this->error('  ✗ User role methods testing failed: ' . $e->getMessage());
            return 1;
        }

        $this->newLine();
        $this->info('✅ Roles and Permissions System test completed successfully!');
        $this->info('🎯 System Summary:');
        $this->info('   - 6 roles created with appropriate permissions');
        $this->info('   - 2 default users created with proper role assignments');
        $this->info('   - CheckRole middleware ready for route protection');
        $this->info('   - User model enhanced with role helper methods');
        $this->newLine();
        $this->info('🔑 Default Login Credentials:');
        $this->info('   Superadmin: superadmin@novaerp.com / superadmin123');
        $this->info('   Admin: admin@novaerp.com / admin123');

        return 0;
    }
}
