<?php

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Modules\Academic\Models\ExamType;
use Modules\Academic\Models\AcademicYear;
use Illuminate\Foundation\Testing\RefreshDatabase;

class ExamTypeUpdateTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test that exam type can be updated successfully
     */
    public function test_exam_type_can_be_updated()
    {
        // Create admin user
        $adminUser = User::factory()->create([
            'role' => 'admin',
            'email' => 'admin@update.test',
        ]);

        // Create academic years
        $academicYear1 = AcademicYear::factory()->create([
            'name' => '2023-2024',
            'start_date' => '2023-09-01',
            'end_date' => '2024-06-30',
            'is_active' => false,
        ]);

        $academicYear2 = AcademicYear::factory()->create([
            'name' => '2024-2025',
            'start_date' => '2024-09-01',
            'end_date' => '2025-06-30',
            'is_active' => true,
        ]);

        // Create exam type
        $examType = ExamType::factory()->create([
            'name' => 'Original Exam',
            'description' => 'Original description',
            'academic_year_id' => $academicYear1->id,
            'weight' => 30.00,
            'is_active' => true,
        ]);

        echo "Original exam type:\n";
        echo "  - Name: {$examType->name}\n";
        echo "  - Academic Year: {$academicYear1->name}\n";
        echo "  - Weight: {$examType->weight}\n";
        echo "  - Description: {$examType->description}\n";
        echo "  - Is Active: " . ($examType->is_active ? 'Yes' : 'No') . "\n";

        // Update data
        $updateData = [
            'academic_year_id' => $academicYear2->id,
            'name' => 'Updated Exam Type',
            'description' => 'Updated description for the exam type',
            'weight' => 45.50,
            'is_active' => false,
        ];

        // Test update as admin
        $response = $this->actingAs($adminUser)
            ->put("/exam-types/{$examType->id}", $updateData);

        echo "\nUpdate Response Status: " . $response->getStatusCode() . "\n";

        if ($response->getStatusCode() !== 302) {
            echo "Response Content: " . $response->getContent() . "\n";
        } else {
            echo "Redirect Location: " . $response->headers->get('Location') . "\n";
        }

        // Should redirect to show page
        $response->assertStatus(302);
        $response->assertRedirect(route('exam-types.show', $examType));

        // Verify the exam type was updated in database
        $examType->refresh();

        echo "\nUpdated exam type:\n";
        echo "  - Name: {$examType->name}\n";
        echo "  - Academic Year ID: {$examType->academic_year_id}\n";
        echo "  - Weight: {$examType->weight}\n";
        echo "  - Description: {$examType->description}\n";
        echo "  - Is Active: " . ($examType->is_active ? 'Yes' : 'No') . "\n";

        $this->assertEquals('Updated Exam Type', $examType->name);
        $this->assertEquals($academicYear2->id, $examType->academic_year_id);
        $this->assertEquals(45.50, $examType->weight);
        $this->assertEquals('Updated description for the exam type', $examType->description);
        $this->assertFalse($examType->is_active);

        echo "✓ All fields updated successfully\n";
    }

    /**
     * Test validation errors
     */
    public function test_exam_type_update_validation()
    {
        // Create admin user
        $adminUser = User::factory()->create([
            'role' => 'admin',
            'email' => 'admin@validation.test',
        ]);

        // Create academic year
        $academicYear = AcademicYear::factory()->create();

        // Create exam type
        $examType = ExamType::factory()->create([
            'academic_year_id' => $academicYear->id,
        ]);

        // Test with invalid data
        $invalidData = [
            'academic_year_id' => 999, // Non-existent academic year
            'name' => '', // Empty name
            'weight' => 150, // Weight over 100
            'description' => str_repeat('a', 600), // Description too long
        ];

        $response = $this->actingAs($adminUser)
            ->put("/exam-types/{$examType->id}", $invalidData);

        echo "Validation Response Status: " . $response->getStatusCode() . "\n";

        // Should redirect back with errors
        $response->assertStatus(302);
        $response->assertSessionHasErrors([
            'academic_year_id',
            'name',
            'weight',
            'description'
        ]);

        echo "✓ Validation errors detected correctly\n";
    }

    /**
     * Test that non-admin cannot update
     */
    public function test_non_admin_cannot_update()
    {
        // Create student user
        $studentUser = User::factory()->create([
            'role' => 'student',
            'email' => 'student@update.test',
        ]);

        // Create academic year and exam type
        $academicYear = AcademicYear::factory()->create();
        $examType = ExamType::factory()->create([
            'academic_year_id' => $academicYear->id,
        ]);

        // Try to update as student
        $response = $this->actingAs($studentUser)
            ->put("/exam-types/{$examType->id}", [
                'name' => 'Hacked Name',
                'academic_year_id' => $academicYear->id,
                'weight' => 50,
            ]);

        echo "Student Update Response Status: " . $response->getStatusCode() . "\n";

        // Should be forbidden
        $response->assertStatus(403);

        echo "✓ Student correctly blocked from updating\n";
    }
}
