<?php

namespace App\Http\Requests;

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

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

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

        $rules = [
            'provider_id' => ['sometimes', 'integer', 'exists:providers,id'],

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

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

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

        return $rules;
    }

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