<?php

namespace App\Http\Requests;

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

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

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

        $rules = [
            'schedule_id'        => ['sometimes', 'integer', 'exists:schedules,id'],
            'origin'             => ['sometimes', 'string', Rule::in(['provider', 'client'])],
            'origin_id'          => ['sometimes', 'integer'],
            'stars'              => ['sometimes', 'numeric', 'min:0', 'max:5'],
            'comment'            => ['nullable', 'string'],
            'improvements_ids'   => ['nullable', 'array'],
            'improvements_ids.*' => ['integer', 'exists:improvement_types,id'],
            'block_provider'     => ['sometimes', 'boolean'],
            'block_client'       => ['sometimes', 'boolean'],
            'favorite_provider'  => ['sometimes', 'boolean'],
            'photos'             => ['sometimes', 'array', 'max:5'],
            'photos.*'           => ['file', 'image', 'mimes:jpg,jpeg,png,webp', 'max:10240'],
        ];

        if ($this->isMethod('POST')) {
            $scheduleId = $this->input('schedule_id');
            $origin     = $this->input('origin');
            $originId   = $this->input('origin_id');

            $rules['schedule_id'] = ['required', 'integer', 'exists:schedules,id'];
            $rules['origin']      = ['required', 'string', Rule::in(['provider', 'client'])];

            $rules['origin_id'] = [
                'required',
                'integer',
                Rule::unique('reviews', 'origin_id')
                    ->where('schedule_id', $scheduleId)
                    ->where('origin', $origin)
                    ->whereNull('deleted_at')
                    ->ignore($reviewId),
            ];

            $rules['stars']              = ['required', 'numeric', 'min:0', 'max:5'];
            $rules['improvements_ids']   = ['sometimes', 'array'];
            $rules['improvements_ids.*'] = ['integer', 'exists:improvement_types,id'];
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'origin_id.unique' => __('validation.custom.review.already_reviewed'),
            'origin.in'        => __('validation.custom.review.invalid_origin'),
        ];
    }
}
