<?php

namespace App\Http\Requests\Call;

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

class UpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return auth()->user()->telephone_id == $this->call->telephone_id;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, ValidationRule|array|string>
     */
    public function rules(): array
    {
        return [
            'category_id' => 'required|integer',
            'subcategory_id' => 'required|integer',
            'description' => 'string',
        ];
    }

    public function after(): array
    {
        return [
            function (Validator $validator) {
                $condition = Category::query()->where([
                    ['category_id', '=', $this->category_id],
                    ['subcategory_id', '=', $this->subcategory_id]
                ])->exists();

                if (!$condition) {
                    $validator->errors()->add(
                        'category',
                        __('messages.combination_of_category_and_subcategory_does_not_exist')
                    );
                }
            }
        ];
    }
}
