<?php

namespace Tests\Feature;

use App\Livewire\Leave\LeaveApplicationIndex;
use App\Models\LeaveApplication;
use App\Models\Role;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Tests\TestCase;

class LeaveTest extends TestCase
{
    use RefreshDatabase;

    protected function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }

    public function test_authenticated_user_can_access_leave_applications_page(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        $response = $this->get('/leave-applications');
        $response->assertStatus(200);
    }

    public function test_livewire_can_submit_and_approve_leave_application(): void
    {
        $admin = User::where('email', 'admin@smkn1gunungagung.sch.id')->first();
        $admin->update(['force_password_change' => false]);
        $this->actingAs($admin);

        $guruRole = Role::where('name', 'guru')->first();
        $guru = User::factory()->create(['role_id' => $guruRole->id]);

        // Submit
        Livewire::test(LeaveApplicationIndex::class)
            ->set('target_user_id', $guru->id)
            ->set('type', 'izin')
            ->set('start_date', '2026-09-01')
            ->set('end_date', '2026-09-02')
            ->set('reason', 'Izin Keperluan Dinas')
            ->call('save')
            ->assertHasNoErrors();

        $app = LeaveApplication::where('user_id', $guru->id)->first();
        $this->assertNotNull($app);

        // Approve
        Livewire::test(LeaveApplicationIndex::class)
            ->call('openApprovalModal', $app->id)
            ->set('approval_notes', 'Approved by test')
            ->call('approve')
            ->assertHasNoErrors();

        $this->assertEquals('approved', $app->fresh()->status);
    }
}
