<?php

namespace Tests\Feature;

use App\Filament\Pages\OCRRecordList;
use App\Filament\Pages\OCRRecordView;
use App\Filament\Pages\UploadExamPaper;
use App\Models\OCRRecord;
use App\Models\Student;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Livewire\Livewire;
use Tests\TestCase;

class OCRPageTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        // Create an admin user if needed, or just a user for authentication
        $this->actingAs(User::factory()->create());
    }

    public function test_can_render_ocr_record_list_page()
    {
        Livewire::test(OCRRecordList::class)
            ->assertSuccessful();
    }

    public function test_can_render_upload_exam_paper_page()
    {
        Livewire::test(UploadExamPaper::class)
            ->assertSuccessful();
    }

    public function test_can_render_ocr_record_view_page()
    {
        // Create a dummy record
        $student = Student::factory()->create();
        $record = OCRRecord::create([
            'id' => 'ocr_test_' . uniqid(),
            'student_id' => $student->student_id,
            'image_path' => 'test.jpg',
            'image_filename' => 'test.jpg',
            'status' => 'pending',
        ]);

        // Test the page with the record ID
        Livewire::test(OCRRecordView::class, ['recordId' => $record->id])
            ->assertSuccessful();
    }

    public function test_upload_exam_paper_flow()
    {
        Storage::fake('public');
        
        // Create teacher and student
        $teacher = \App\Models\Teacher::factory()->create();
        $student = \App\Models\Student::factory()->create([
            'teacher_id' => $teacher->teacher_id
        ]);
        
        $file = UploadedFile::fake()->image('exam.jpg');

        Livewire::test(UploadExamPaper::class)
            ->set('selectedTeacherId', $teacher->teacher_id)
            ->set('selectedStudentId', $student->student_id)
            ->set('uploadedImage', $file)
            ->call('submitUpload')
            ->assertHasNoErrors();
            
        // Verify record created
        $this->assertDatabaseHas('ocr_records', [
            'student_id' => $student->student_id,
        ]);
    }
}
