<?php

namespace Tests\Unit\Services\Attendance;

use App\Services\Attendance\AttendanceSummaryRebuildService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class AttendanceSummaryRebuildServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_rebuild_inserts_summary_rows(): void
    {
        DB::table('attendance_data')->insert([
            [
                'class_id' => 1,
                'class_section_id' => 10,
                'student_id' => 1,
                'school_id' => 'S1',
                'date' => '2025-02-01',
                'status' => 'present',
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
            [
                'class_id' => 1,
                'class_section_id' => 10,
                'student_id' => 1,
                'school_id' => 'S1',
                'date' => '2025-02-02',
                'status' => 'absent',
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
            [
                'class_id' => 1,
                'class_section_id' => 11,
                'student_id' => 2,
                'school_id' => 'S1',
                'date' => '2025-02-02',
                'status' => 'late',
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
        ]);

        $service = new AttendanceSummaryRebuildService();
        $result = $service->rebuild();

        $this->assertSame(2, $result['inserted']);
        $this->assertDatabaseHas('attendance_record', [
            'student_id' => 1,
            'total_presence' => 1,
            'total_absence' => 1,
            'total_late' => 0,
            'total_attendance' => 2,
        ]);
        $this->assertDatabaseHas('attendance_record', [
            'student_id' => 2,
            'total_presence' => 0,
            'total_absence' => 0,
            'total_late' => 1,
            'total_attendance' => 1,
        ]);
    }
}
