<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

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

    public function rules(): array
    {
        $itemId   = $this->route('id');
        $reviewId = $this->input('review_id');

        $rules = [
            'review_id'           => ['sometimes', 'integer', 'exists:reviews,id'],
            'improvement_type_id' => ['sometimes', 'integer', 'exists:improvement_types,id'],
        ];

        if ($this->isMethod('POST')) {
            $rules['review_id'] = ['required', 'integer', 'exists:reviews,id'];

            $rules['improvement_type_id'] = [
                'required',
                'integer',
                'exists:improvement_types,id',
                Rule::unique('reviews_improvements', 'improvement_type_id')
                    ->where('review_id', $reviewId)
                    ->whereNull('deleted_at')
                    ->ignore($itemId),
            ];
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'improvement_type_id.unique' => __('validation.custom.review_improvement.already_exists'),
        ];
    }
}
