<?php

namespace App\Http\Requests;

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

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

    public function rules(): array
    {
        $clientId   = $this->input('client_id');
        $favoriteId = $this->route('id');

        $rules = [
            'client_id' => ['sometimes', 'integer', 'exists:clients,id'],

            'provider_id' => [
                'sometimes',
                'integer',
                'exists:providers,id',
                Rule::unique('client_favorite_providers', 'provider_id')
                    ->where('client_id', $clientId)
                    ->whereNull('deleted_at')
                    ->ignore($favoriteId),
            ],

            'notes' => ['nullable', 'string', 'max:1000'],
        ];

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

            $rules['provider_id'] = [
                'required',
                'integer',
                'exists:providers,id',
                Rule::unique('client_favorite_providers', 'provider_id')
                    ->where('client_id', $clientId)
                    ->whereNull('deleted_at')
                    ->ignore($favoriteId),
            ];
        }

        return $rules;
    }

    public function messages(): array
    {
        return [
            'client_id.required'   => __('requests.client_favorite_provider.client_required'),
            'client_id.exists'     => __('requests.client_favorite_provider.client_not_found'),
            'provider_id.required' => __('requests.client_favorite_provider.provider_required'),
            'provider_id.exists'   => __('requests.client_favorite_provider.provider_not_found'),
            'provider_id.unique'   => __('requests.client_favorite_provider.already_favorite'),
            'notes.max'            => __('requests.client_favorite_provider.notes_max'),
        ];
    }
}
