<?php

namespace Tests\Unit\Services\Attendance;

use App\Models\AttendanceTracking;
use App\Services\Attendance\AttendanceConsequenceService;
use App\Services\EmailService;
use App\Services\Notifications\UserNotificationDispatchService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Mockery;
use Tests\TestCase;

class AttendanceConsequenceServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_send_follow_up_requires_parent_email(): void
    {
        $service = new AttendanceConsequenceService(
            Mockery::mock(EmailService::class),
            Mockery::mock(UserNotificationDispatchService::class)
        );

        $result = $service->sendFollowUp([
            'parent' => ['user_id' => 5],
        ]);

        $this->assertFalse($result['ok']);
    }

    public function test_send_follow_up_marks_tracking_and_notifies(): void
    {
        \Illuminate\Support\Facades\DB::table('students')->insert([
            'id' => 1,
            'school_id' => 1,
            'parent_id' => 1,
            'firstname' => 'Student',
            'lastname' => 'One',
            'dob' => '2015-01-01',
            'age' => 10,
            'gender' => 'Male',
            'is_active' => 1,
            'photo_consent' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
        ]);

        AttendanceTracking::query()->create([
            'student_id' => 1,
            'date' => now(),
            'is_reported' => 1,
            'reason' => 'ABS_2',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $email = Mockery::mock(EmailService::class);
        $email->shouldReceive('send')->once()->andReturn(true);

        $notifier = Mockery::mock(UserNotificationDispatchService::class);
        $notifier->shouldReceive('notifyUser')->once();

        $service = new AttendanceConsequenceService($email, $notifier);

        $result = $service->sendFollowUp([
            'student_id' => 1,
            'parent' => ['email' => 'parent@example.com', 'user_id' => 5],
            'student' => ['firstname' => 'A', 'lastname' => 'B'],
            'tracking_id' => 1,
            'html' => '<p>Test</p>',
        ]);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('attendance_tracking', [
            'id' => 1,
            'is_notified' => 1,
        ]);
    }
}
