<?php

namespace App\Http\Requests;

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

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

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

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

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

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

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

        return $rules;
    }

    public function messages(): array
    {
        return [
            'client_id.required'   => __('validation.required', ['attribute' => __('validation.attributes.client')]),
            'client_id.exists'     => __('validation.exists', ['attribute' => __('validation.attributes.client')]),
            'provider_id.required' => __('validation.required', ['attribute' => __('validation.attributes.provider')]),
            'provider_id.exists'   => __('validation.exists', ['attribute' => __('validation.attributes.provider')]),
            'provider_id.unique'   => __('validation.custom.client_provider_block.already_blocked'),
        ];
    }
}
