<?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 ExamTypeEditTest extends TestCase
{
    use RefreshDatabase;

    /**
     * Test that the edit page provides all required data
     */
    public function test_edit_page_provides_required_data()
    {
        // Create admin user
        $adminUser = User::factory()->create([
            'role' => 'admin',
            'email' => 'admin@edit.test',
        ]);

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

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

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

        // Test as admin with Inertia headers
        $response = $this->actingAs($adminUser)
            ->withHeaders([
                'X-Inertia' => 'true',
                'X-Inertia-Version' => '1.0',
            ])
            ->get("/exam-types/{$examType->id}/edit");

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

        $response->assertStatus(200);

        // Check if it's an Inertia response
        if ($response->headers->has('x-inertia')) {
            echo "✓ Inertia response detected\n";
            
            $content = $response->getContent();
            $data = json_decode($content, true);
            
            if ($data) {
                echo "✓ Valid JSON response\n";
                echo "Component: " . ($data['component'] ?? 'N/A') . "\n";
                
                // Check component
                $this->assertEquals('Academic/ExamTypes/Edit', $data['component']);
                
                // Check props
                $this->assertArrayHasKey('props', $data);
                $props = $data['props'];
                
                // Check examType prop
                $this->assertArrayHasKey('examType', $props);
                $examTypeData = $props['examType'];
                
                echo "✓ ExamType data found\n";
                echo "  - ID: " . $examTypeData['id'] . "\n";
                echo "  - Name: " . $examTypeData['name'] . "\n";
                echo "  - Academic Year ID: " . $examTypeData['academic_year_id'] . "\n";
                echo "  - Weight: " . $examTypeData['weight'] . "\n";
                echo "  - Is Active: " . ($examTypeData['is_active'] ? 'Yes' : 'No') . "\n";
                
                // Check academicYears prop (this was missing before)
                $this->assertArrayHasKey('academicYears', $props);
                $academicYearsData = $props['academicYears'];
                
                echo "✓ Academic Years data found\n";
                $this->assertIsArray($academicYearsData);
                $this->assertGreaterThanOrEqual(2, count($academicYearsData));
                
                echo "  - Found " . count($academicYearsData) . " academic years\n";
                
                // Check structure of academic years
                foreach ($academicYearsData as $index => $academicYear) {
                    $this->assertArrayHasKey('id', $academicYear);
                    $this->assertArrayHasKey('name', $academicYear);
                    echo "  - Academic Year {$index}: ID={$academicYear['id']}, Name={$academicYear['name']}\n";
                }
                
                // Verify the exam type's academic year is in the list
                $examTypeAcademicYearFound = false;
                foreach ($academicYearsData as $academicYear) {
                    if ($academicYear['id'] == $examTypeData['academic_year_id']) {
                        $examTypeAcademicYearFound = true;
                        echo "✓ Exam type's academic year found in the list\n";
                        break;
                    }
                }
                
                $this->assertTrue($examTypeAcademicYearFound, 'Exam type\'s academic year should be in the academic years list');
                
            } else {
                echo "✗ Invalid JSON response\n";
                $this->fail('Invalid JSON response');
            }
        } else {
            echo "✗ Not an Inertia response\n";
            $this->fail('Expected Inertia response');
        }
    }

    /**
     * Test that create page also provides academic years
     */
    public function test_create_page_provides_academic_years()
    {
        // Create admin user
        $adminUser = User::factory()->create([
            'role' => 'admin',
            'email' => 'admin@create.test',
        ]);

        // Create academic years
        AcademicYear::factory()->count(2)->create();

        // Test as admin with Inertia headers
        $response = $this->actingAs($adminUser)
            ->withHeaders([
                'X-Inertia' => 'true',
                'X-Inertia-Version' => '1.0',
            ])
            ->get('/exam-types/create');

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

        $response->assertStatus(200);

        if ($response->headers->has('x-inertia')) {
            echo "✓ Create page Inertia response detected\n";
            
            $content = $response->getContent();
            $data = json_decode($content, true);
            
            if ($data) {
                echo "✓ Create page Valid JSON response\n";
                echo "Create Component: " . ($data['component'] ?? 'N/A') . "\n";
                
                // Check component
                $this->assertEquals('Academic/ExamTypes/Create', $data['component']);
                
                // Check props
                $this->assertArrayHasKey('props', $data);
                $props = $data['props'];
                
                // Check academicYears prop
                $this->assertArrayHasKey('academicYears', $props);
                $academicYearsData = $props['academicYears'];
                
                echo "✓ Create page Academic Years data found\n";
                $this->assertIsArray($academicYearsData);
                $this->assertGreaterThanOrEqual(2, count($academicYearsData));
                
                echo "  - Create page found " . count($academicYearsData) . " academic years\n";
                
            } else {
                echo "✗ Create page Invalid JSON response\n";
                $this->fail('Create page Invalid JSON response');
            }
        } else {
            echo "✗ Create page Not an Inertia response\n";
            $this->fail('Create page Expected Inertia response');
        }
    }
}
