<?php

namespace Tests\Unit\Services\ClassPreparation;

use App\Services\ClassPreparation\ClassPreparationService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ClassPreparationServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_list_prep_returns_sections_and_totals(): void
    {
        $this->seedPrepData();

        $service = app(ClassPreparationService::class);
        $payload = $service->listPrep('2025-2026', 'Fall');

        $this->assertSame('2025-2026', $payload['schoolYear']);
        $this->assertSame('Fall', $payload['semester']);
        $this->assertNotEmpty($payload['results']);
        $this->assertArrayHasKey('Small Table', $payload['totals']);
    }

    public function test_mark_printed_creates_logs(): void
    {
        $this->seedPrepData();

        $service = app(ClassPreparationService::class);
        $count = $service->markPrinted('2025-2026', 'Fall', [101]);

        $this->assertSame(1, $count);
        $this->assertDatabaseHas('class_preparation_log', [
            'class_section_id' => 101,
            'school_year' => '2025-2026',
        ]);
    }

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

        DB::table('classSection')->insert([
            'id' => 1,
            'class_id' => 1,
            'class_section_id' => 101,
            'class_section_name' => '1-A',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('students')->insert([
            'school_id' => 'S-1',
            'firstname' => 'Student',
            'lastname' => 'One',
            'age' => 8,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
            'is_active' => 1,
        ]);

        DB::table('student_class')->insert([
            'student_id' => 1,
            'class_section_id' => 101,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        DB::table('inventory_categories')->insert([
            'type' => 'classroom',
            'name' => 'Small Table',
        ]);

        DB::table('inventory_items')->insert([
            'type' => 'classroom',
            'category_id' => 1,
            'name' => 'Small Table',
            'quantity' => 10,
            'good_qty' => 10,
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);
    }
}
