<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\User;
use Modules\Academic\Models\ExamType;
use Modules\Academic\Models\AcademicYear;
use Illuminate\Support\Facades\Gate;

class DebugExamTypeAuth extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'debug:exam-type-auth';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Debug ExamType authorization issues';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Debugging ExamType Authorization Issues...');
        $this->info('==========================================');
        
        // Get admin user
        $adminUser = User::where('role', 'admin')->first();
        if (!$adminUser) {
            $this->error('No admin user found!');
            return 1;
        }
        
        $this->info("Admin user: {$adminUser->email} (Role: {$adminUser->role})");
        
        // Get or create exam type
        $examType = ExamType::first();
        if (!$examType) {
            $academicYear = AcademicYear::first();
            if (!$academicYear) {
                $this->error('No academic year found!');
                return 1;
            }
            
            $examType = ExamType::create([
                'name' => 'Debug Test Exam',
                'description' => 'Test exam for debugging',
                'academic_year_id' => $academicYear->id,
                'is_active' => true,
            ]);
        }
        
        $this->info("Exam type: {$examType->name} (ID: {$examType->id})");
        
        // Test individual policy methods
        $this->info('Testing individual policy methods...');
        
        try {
            $policy = Gate::getPolicyFor(ExamType::class);
            if (!$policy) {
                $this->error('No policy found for ExamType!');
                return 1;
            }
            
            $this->info("Policy class: " . get_class($policy));
            
            // Test viewAny
            $canViewAny = $policy->viewAny($adminUser);
            $this->line("viewAny: " . ($canViewAny ? 'ALLOWED' : 'DENIED'));
            
            // Test view
            $canView = $policy->view($adminUser, $examType);
            $this->line("view: " . ($canView ? 'ALLOWED' : 'DENIED'));
            
            // Test create
            $canCreate = $policy->create($adminUser);
            $this->line("create: " . ($canCreate ? 'ALLOWED' : 'DENIED'));
            
            // Test update
            $canUpdate = $policy->update($adminUser, $examType);
            $this->line("update: " . ($canUpdate ? 'ALLOWED' : 'DENIED'));
            
            // Test delete
            $canDelete = $policy->delete($adminUser, $examType);
            $this->line("delete: " . ($canDelete ? 'ALLOWED' : 'DENIED'));
            
        } catch (\Exception $e) {
            $this->error("Error testing policy methods: " . $e->getMessage());
        }
        
        // Test using Gate facade
        $this->info('Testing using Gate facade...');
        
        try {
            $canViewAnyGate = Gate::forUser($adminUser)->allows('viewAny', ExamType::class);
            $this->line("Gate viewAny: " . ($canViewAnyGate ? 'ALLOWED' : 'DENIED'));
            
            $canViewGate = Gate::forUser($adminUser)->allows('view', $examType);
            $this->line("Gate view: " . ($canViewGate ? 'ALLOWED' : 'DENIED'));
            
            $canCreateGate = Gate::forUser($adminUser)->allows('create', ExamType::class);
            $this->line("Gate create: " . ($canCreateGate ? 'ALLOWED' : 'DENIED'));
            
            $canUpdateGate = Gate::forUser($adminUser)->allows('update', $examType);
            $this->line("Gate update: " . ($canUpdateGate ? 'ALLOWED' : 'DENIED'));
            
            $canDeleteGate = Gate::forUser($adminUser)->allows('delete', $examType);
            $this->line("Gate delete: " . ($canDeleteGate ? 'ALLOWED' : 'DENIED'));
            
        } catch (\Exception $e) {
            $this->error("Error testing Gate: " . $e->getMessage());
        }
        
        // Test what happens when we simulate the controller authorization
        $this->info('Testing controller authorization simulation...');
        
        try {
            // Simulate what happens in the controller
            auth()->login($adminUser);
            
            $this->line("Authenticated user: " . (auth()->check() ? auth()->user()->email : 'NONE'));
            $this->line("Authenticated user role: " . (auth()->check() ? auth()->user()->role : 'NONE'));
            
            // Test authorization as it would happen in controller
            $canViewInController = auth()->user()->can('view', $examType);
            $this->line("Controller can view: " . ($canViewInController ? 'ALLOWED' : 'DENIED'));
            
            $canUpdateInController = auth()->user()->can('update', $examType);
            $this->line("Controller can update: " . ($canUpdateInController ? 'ALLOWED' : 'DENIED'));
            
        } catch (\Exception $e) {
            $this->error("Error testing controller simulation: " . $e->getMessage());
        }
        
        $this->info('==========================================');
        
        return 0;
    }
}
