<?php

namespace Tests\Unit\Services\Attendance;

use App\Services\Attendance\AttendanceAutoPublishJobService;
use App\Services\Attendance\AttendanceAutoPublishService;
use DateTimeImmutable;
use DateTimeZone;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class AttendanceAutoPublishJobServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_run_publishes_due_records(): void
    {
        $autoPublish = new AttendanceAutoPublishService();
        $service = new AttendanceAutoPublishJobService($autoPublish);

        $now = new DateTimeImmutable('2025-03-01 10:00:00', new DateTimeZone('UTC'));
        $cutoff = $autoPublish->secondSundayBackwardDate($now);

        DB::table('attendance_day')->insert([
            [
                'class_section_id' => 1,
                'date' => '2025-03-01',
                'status' => 'submitted',
                'auto_publish_at' => '2025-03-01 09:00:00',
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
            [
                'class_section_id' => 2,
                'date' => $cutoff,
                'status' => 'submitted',
                'auto_publish_at' => null,
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
            [
                'class_section_id' => 3,
                'date' => '2025-02-20',
                'status' => 'draft',
                'auto_publish_at' => null,
                'semester' => 'Spring',
                'school_year' => '2024-2025',
            ],
        ]);

        $result = $service->run($now);

        $this->assertSame(2, $result['published']);
        $this->assertDatabaseHas('attendance_day', [
            'class_section_id' => 1,
            'status' => 'published',
        ]);
        $this->assertDatabaseHas('attendance_day', [
            'class_section_id' => 2,
            'status' => 'published',
        ]);
        $this->assertDatabaseHas('attendance_day', [
            'class_section_id' => 3,
            'status' => 'draft',
        ]);
    }
}
