<?php

namespace Modules\HR\Http\Requests\Holiday;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
use Modules\Core\Enums\StatusEnum;
use Modules\Core\Traits\FailedValidation;

class UpdateHolidayRequest extends FormRequest
{
    use FailedValidation;

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     */
    public function rules(): array
    {
        $holidayId = $this->route('holiday');

        return [
            'holiday_group_id' => [
                'required',
                'integer',
                'exists:holiday_groups,id'
            ],
            'title' => [
                'required',
                'string',
                'max:255'
            ],
            'holiday_date' => [
                'required',
                'date',
                'date_format:Y-m-d',
                Rule::unique('holidays', 'holiday_date')
                    ->ignore($holidayId)
                    ->where(function ($query) {
                        return $query->where('holiday_group_id', $this->holiday_group_id);
                    })
            ],
            'is_optional' => [
                'nullable',
                'boolean'
            ],
            'remarks' => [
                'nullable',
                'string',
                'max:1000'
            ],
            'status' => [
                'nullable',
                Rule::in(StatusEnum::casesAsArray())
            ],
        ];
    }

    /**
     * Get custom messages for validator errors.
     */
    public function messages(): array
    {
        return [
            'holiday_date.unique' => 'A holiday config has already been configured for this group on the selected date.',
        ];
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'holiday_group_id' => 'holiday group',
            'holiday_date'     => 'holiday date',
            'is_optional'      => 'optional flag',
        ];
    }

    /**
     * Handle a passed validation attempt.
     */
    protected function passedValidation(): void
    {
        $this->merge([
            'is_optional' => $this->boolean('is_optional', false),
            'status'      => $this->status ?? StatusEnum::ACTIVE,
        ]);
    }
}
