<?php

namespace App\Modules\HR\Shifts\Requests;

use App\Modules\HR\Shifts\Support\ShiftWeekday;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateShiftRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('shifts.update', $this->route('shift')) ?? false;
    }

    protected function prepareForValidation(): void
    {
        $wd = $this->input('working_days');
        if (is_array($wd)) {
            $this->merge(['working_days' => array_values(array_filter($wd, fn ($v) => $v !== null && $v !== ''))]);
        }
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:160'],
            'type' => ['required', Rule::in(['fixed', 'flexible', 'rotational', 'factory', 'split', 'night', 'seasonal'])],
            'start_time' => ['required', 'date_format:H:i'],
            'end_time' => ['required', 'date_format:H:i'],
            'grace_minutes' => ['nullable', 'integer', 'min:0', 'max:600'],
            'late_after_minutes' => ['nullable', 'integer', 'min:0', 'max:600'],
            'overtime_after_minutes' => ['nullable', 'integer', 'min:0', 'max:1440'],
            'break_minutes' => ['nullable', 'integer', 'min:0', 'max:600'],
            'working_days' => ['required', 'array', 'min:1'],
            'working_days.*' => ['required', 'string', Rule::in(ShiftWeekday::all())],
            'is_night_shift' => ['sometimes', 'boolean'],
            'flexible_start' => ['nullable', 'date_format:H:i'],
            'flexible_end' => ['nullable', 'date_format:H:i'],
            'split_second_start' => ['nullable', 'date_format:H:i'],
            'split_second_end' => ['nullable', 'date_format:H:i'],
            'seasonal_from' => ['nullable', 'date'],
            'seasonal_to' => ['nullable', 'date', 'after_or_equal:seasonal_from'],
        ];
    }

    protected function passedValidation(): void
    {
        $this->merge(['is_night_shift' => $this->boolean('is_night_shift')]);
    }
}

