<?php

namespace App\Http\Requests\Admin\AcademySchedule;

use App\Enums\DayOfWeekEnum;
use App\Models\Academy;
use App\Models\Court;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class StoreAcademyScheduleRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'academy_id'  => ['required', 'integer', 'exists:academies,id'],
            'court_id'    => ['required', 'integer', 'exists:courts,id'],
            'days'        => ['required', 'array', 'min:1'],
            'days.*'      => ['integer', 'in:' . implode(',', DayOfWeekEnum::values())],
            'start_time'  => ['required', 'date_format:H:i'],
            'end_time'    => ['required', 'date_format:H:i', 'after:start_time'],
            'start_date'  => ['required', 'date'],
            'end_date'    => ['required', 'date', 'after_or_equal:start_date'],
            'is_active'   => ['nullable', 'boolean'],
        ];
    }

    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $academy = Academy::find($this->input('academy_id'));
            if (!$academy?->game_id) {
                return;
            }
            $courtBelongsToGame = Court::where('id', $this->input('court_id'))
                ->where('game_id', $academy->game_id)
                ->exists();
            if (!$courtBelongsToGame) {
                $validator->errors()->add('court_id', __('dashboard.court_must_belong_to_academy_game'));
            }
        });
    }
}
