<?php

namespace Tests\Unit;

use App\Models\Company;
use App\Models\LeaveType;
use App\Models\User;
use App\Services\Leave\LeaveDayCalculator;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LeaveDayCalculatorTest extends TestCase
{
    use RefreshDatabase;

    public function test_same_day_full_leave_counts_as_one_day_on_weekend_when_excluded(): void
    {
        $company = Company::query()->create([
            'name' => 'ACME',
            'short_name' => 'ACME',
            'email' => 'co@acme.test',
            'status' => 'active',
        ]);

        $user = User::factory()->create([
            'company_id' => $company->id,
            'user_type' => User::USER_TYPE_STAFF,
        ]);

        $leaveType = LeaveType::query()->create([
            'company_id' => $company->id,
            'name' => 'Casual',
            'short_code' => 'CL',
            'is_paid' => true,
            'total_leaves' => 12,
            'weekend_policy' => 'exclude',
            'holiday_policy' => 'exclude',
            'apply_to_all' => true,
        ]);

        $saturday = Carbon::parse('2026-06-20')->startOfDay(); // Saturday
        $this->assertTrue($saturday->isSaturday());

        $calc = (new LeaveDayCalculator())->calculate($user, $leaveType, $saturday, $saturday->copy(), false);

        $this->assertSame(1.0, $calc['chargeable_days']);
        $this->assertSame(1.0, $calc['calendar_days']);
    }

    public function test_same_day_half_leave_counts_as_half_day(): void
    {
        $company = Company::query()->create([
            'name' => 'ACME2',
            'short_name' => 'ACM2',
            'email' => 'co2@acme.test',
            'status' => 'active',
        ]);

        $user = User::factory()->create([
            'company_id' => $company->id,
            'user_type' => User::USER_TYPE_STAFF,
        ]);

        $leaveType = LeaveType::query()->create([
            'company_id' => $company->id,
            'name' => 'Casual',
            'short_code' => 'CL',
            'is_paid' => true,
            'total_leaves' => 12,
            'weekend_policy' => 'exclude',
            'holiday_policy' => 'exclude',
            'apply_to_all' => true,
        ]);

        $day = Carbon::parse('2026-06-18')->startOfDay();
        $calc = (new LeaveDayCalculator())->calculate($user, $leaveType, $day, $day->copy(), true);

        $this->assertSame(0.5, $calc['chargeable_days']);
    }
}
