<?php

namespace Tests\Unit\Services\Exams;

use App\Services\Exams\ExamDraftConfigService;
use App\Services\Exams\ExamDraftFileService;
use App\Services\Exams\ExamDraftTeacherService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ExamDraftTeacherServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_store_creates_draft(): void
    {
        $this->seedConfig();
        $teacherId = $this->seedTeacher();
        $classSectionId = $this->seedClassSection();
        $this->seedAssignment($teacherId, $classSectionId);

        $service = new ExamDraftTeacherService(new ExamDraftConfigService(), new ExamDraftFileService());

        $file = UploadedFile::fake()->create('draft.docx', 10, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        $result = $service->store($teacherId, [
            'class_section_id' => $classSectionId,
            'exam_type' => 'Final Exam',
            'description' => 'Draft',
        ], $file);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('exam_drafts', [
            'teacher_id' => $teacherId,
            'class_section_id' => $classSectionId,
            'status' => 'submitted',
        ]);
    }

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedTeacher(): int
    {
        return DB::table('users')->insertGetId([
            'firstname' => 'Teacher',
            'lastname' => 'User',
            'cellphone' => '1111111111',
            'email' => 'teacher.exam@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);
    }

    private function seedClassSection(): int
    {
        DB::table('classSection')->insert([
            'class_id' => 1,
            'class_section_id' => 801,
            'class_section_name' => '8A',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return 801;
    }

    private function seedAssignment(int $teacherId, int $classSectionId): void
    {
        DB::table('teacher_class')->insert([
            'teacher_id' => $teacherId,
            'class_section_id' => $classSectionId,
            'position' => 'main',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }
}
