<?php

namespace App\Http\Requests\V3\Mission\RequestPortal;

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 [
            'rahdaran' => 'array',
            'rahdaran.*' => 'exists:rahdaran,id',
            'requested_machines' => 'required|array',
            'type' => 'required|in:1,2',
            'zone' => 'required|in:1,2,3',
            'start_date' => 'required|date',
            'end_date' => 'required|date',
            'description' => 'string',
            'end_point' => 'required|string',
            'area' => 'required|array',
            'area.type' => 'required|string',
            'area.coordinates' => 'required|array',
            'explanation'  => 'required|string',
            'category_id' => 'required|in:1,2,3',
            'road_observed_id' => 'required_if:category_id,3|exists:road_observeds,id',
        ];
    }

    public function after(): array
    {
        return [
            function (Validator $validator) {
                if ($this->type == 1){
                    $start = Carbon::parse($this->start_date);
                    $end = Carbon::parse($this->end_date);

                    if ($start->diffInMinutes($end) > 480){
                        $validator->errors()->add(
                            'end_date',
                           'مدت  زمان مأموریت ساعتی نباید بیشتر از ۸ ساعت باشد.'
                        );
                    }
                }
            }
        ];
    }
}
