<?php

namespace App\Http\Requests\V3\RoadItem\Operator;

use App\Models\Mission;
use Carbon\Carbon;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class StoreRequest extends FormRequest
{
    /**
     * 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.
     *
     * @return array<string, ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'mission_id' => 'required|integer|exists:missions,id',
            'start_point' => 'required',
            'item_id' => 'required|integer',
            'sub_item_id' => 'required|integer',
            'amount' => 'required|numeric',
            'observed_item_id' => 'integer|exists:observed_items,id',
            'activity_date' => 'required|date_format:Y-m-d',
            'activity_time' => 'required|date_format:H:i',
            'before_image' => 'image|max:4096',
            'after_image' => 'image|max:4096',
        ];
    }

    public function attributes(): array
    {
        return [
            'activity_date' => 'تاریخ فعالیت',
            'activity_time' => 'ساعت فعالیت',
        ];
    }

    public function after(): array
    {
        return [
            function (Validator $validator) {

                $mission = Mission::query()->find($this->mission_id);

                $startTime = Carbon::parse($mission->start_time);
                $finishTime   = Carbon::parse($mission->finish_time);
                $activityTime = Carbon::parse("{$this->activity_date} {$this->activity_time}");

                if (! $activityTime->between($startTime, $finishTime, true)) {
                    $validator->errors()->add('activity_time', 'زمان گزارش باید بین بازه مأموریت باشد.');
                }
            }
        ];
    }
}
