<?php

declare(strict_types=1);

namespace App\Services\Vacation;

use App\Enums\ApprovalStatus;
use App\Models\User;
use App\Models\Vacation;
use App\Notifications\VacationApprovedNotification;
use App\Notifications\VacationSubmittedNotification;
use App\Services\Leave\LeaveDaysCalculator;
use Carbon\Carbon;
use Illuminate\Support\Facades\Notification;

class VacationService
{
    public function __construct(
        private readonly LeaveDaysCalculator $leaveDaysCalculator,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public function submit(array $data): Vacation
    {
        $startDate = Carbon::parse($data['start_date']);
        $endDate = Carbon::parse($data['end_date']);

        $vacation = Vacation::create([
            ...$data,
            'days' => $this->leaveDaysCalculator->between($startDate, $endDate),
            'status' => ApprovalStatus::Pending,
        ]);

        Notification::send(
            User::role('hr_manager')->get(),
            new VacationSubmittedNotification($vacation),
        );

        return $vacation;
    }

    public function approve(Vacation $vacation, User $approver): void
    {
        $vacation->update([
            'status' => ApprovalStatus::Approved,
            'approved_by' => $approver->id,
            'approved_at' => now(),
        ]);

        Notification::send(
            User::role('hr_manager')->get(),
            new VacationApprovedNotification($vacation),
        );
    }

    public function reject(Vacation $vacation, User $approver): void
    {
        $vacation->update([
            'status' => ApprovalStatus::Rejected,
            'approved_by' => $approver->id,
            'approved_at' => now(),
        ]);
    }
}
