<?php

namespace App\Http\Requests;

use App\Traits\HasResponse;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Validation\Rule;

class ClientAddressRequest extends FormRequest
{
    use HasResponse;

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {

        $rules = [
            'address'            => ['nullable', 'string'],
            'email'             => ['nullable', 'string'],
            'alias'             => ['nullable', 'string'],

            'idclient'          => ['nullable', 'integer', 'validate_ids_exist:Supplier'],
            'idcountry'         => ['nullable', 'numeric', 'validate_ids_exist:Country'],
            'iddepartment'      => ['nullable', 'numeric', 'validate_ids_exist:Department'],
            'idprovince'        => ['nullable', 'numeric', 'validate_ids_exist:Province'],
            'iddistrict'        => ['nullable', 'numeric', 'validate_ids_exist:District'],

            'idcompany' => ['nullable', 'numeric', 'validate_ids_exist:Company'],
        ];

        if ($this->isMethod('POST')) {
            $rules['address']       = ['required', 'string'];
            $rules['email']         = ['nullable', 'string'];
            $rules['alias']         = ['nullable', 'string'];

            $rules['idclient']      = ['nullable', 'integer', 'validate_ids_exist:Supplier'];
            $rules['idcountry']     = ['nullable', 'numeric', 'validate_ids_exist:Country'];
            $rules['iddepartment']  = ['nullable', 'numeric', 'validate_ids_exist:Department'];
            $rules['idprovince']    = ['nullable', 'numeric', 'validate_ids_exist:Province'];
            $rules['iddistrict']    = ['required', 'numeric', 'validate_ids_exist:District'];

            $rules['idcompany']     = ['required', 'numeric', 'validate_ids_exist:Company'];
        }
        return $rules;
    }

    public function failedValidation(Validator $validator)
    {
        $errors = $validator->errors();
        $primerArray = reset($errors);
        $primerError = reset($primerArray);
        $message = $primerError[0];

        throw new HttpResponseException($this->errorResponse($message, 400));
    }
}
