<?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 StoreHolidayRequest 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
    {
        return [
            'holiday_group_id' => [
                'required',
                'integer',
                'exists:holiday_groups,id'
            ],
            'title' => [
                'required',
                'string',
                'max:255'
            ],
            'start_date' => [
                'required',
                'date',
                'date_format:Y-m-d'
            ],
            'end_date' => [
                'nullable',
                'date',
                'date_format:Y-m-d',
                'after_or_equal:start_date'
            ],
            'is_optional' => [
                'nullable',
                'boolean'
            ],
            'remarks' => [
                'nullable',
                'string',
                'max:1000'
            ],
            'status' => [
                'nullable',
                Rule::in(StatusEnum::casesAsArray())
            ],
        ];
    }

    /**
     * Get custom attributes for validator errors.
     */
    public function attributes(): array
    {
        return [
            'holiday_group_id' => 'holiday group',
            'start_date'       => 'start date',
            'end_date'         => 'end 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,
            'end_date'    => $this->end_date ?? $this->start_date,
        ]);
    }
}
