<?php

namespace App\Http\Requests\Admin\Hr;

use App\Enums\LeaveRequestStatus;
use App\Enums\Permission;
use App\Models\LeaveRequest;
use Illuminate\Foundation\Http\FormRequest;

class SubmitLeaveRequest extends FormRequest
{
    public function authorize(): bool
    {
        $user = $this->user();

        if ($user === null || $user->can(Permission::LEAVE_REQUESTS_VERIFY->value)) {
            return false;
        }

        if ($this->isMethod('POST')) {
            return $user->can(Permission::LEAVE_REQUESTS_CREATE->value)
                && $user->employee !== null;
        }

        if (! $user->can(Permission::LEAVE_REQUESTS_UPDATE->value)) {
            return false;
        }

        /** @var LeaveRequest|null $leaveRequest */
        $leaveRequest = $this->route('leaveRequest');

        return $leaveRequest?->status === LeaveRequestStatus::PENDING
            && $user->employee?->id === $leaveRequest->employee_id;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'start_date' => ['required', 'date'],
            'end_date' => ['required', 'date', 'after_or_equal:start_date'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function attributes(): array
    {
        return [
            'start_date' => 'tanggal mulai',
            'end_date' => 'tanggal selesai',
        ];
    }
}
