<?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 SupplierRequest 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 = [
            'rut'               => ['nullable', 'string'],
            'name_rz'           => ['nullable', 'string'],
            'fantasy_name'      => ['nullable', 'string'],
            'web'               => ['nullable', 'string'],
            'giro'              => ['nullable', 'string'],
            'email'             => ['nullable', 'string'],
            'phone'             => ['nullable', 'string'],
            'fax'               => ['nullable', 'string', 'max:15'],
            'type'              => ['nullable', 'numeric', 'min:1', 'max:3'],
            'legal_nature'      => ['nullable', 'numeric', Rule::in([33, 39])],

            'idwaytopay'        => ['nullable', 'numeric', 'validate_ids_exist:WayToPay'],
            'idsegment'         => ['nullable', 'numeric', 'validate_ids_exist:Segment'],
            'idsalesman'        => ['nullable', 'numeric', 'validate_ids_exist:Salesman'],
            'idbussines_area'   => ['nullable', 'numeric', 'validate_ids_exist:BusinessArea'],

            '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'],

            'contacts'          => [
                'nullable',
                'array',
                function ($attribute, $value, $fail) {
                    foreach ($value as $contact) {
                        if (!is_array($contact) || !isset($contact['rut'], $contact['name'],  $contact['charge'])) {
                            $fail("El formato de los contactos es incorrecto. Cada contacto debe tener las propiedades 'rut', 'name', 'phone' y 'charge'.");
                            return $fail;
                        }
                    }
                },
            ],

            'addresses'          => ['nullable', 'array'],
            'addresses.*.id'            => ['nullable', 'numeric'],
            'addresses.*.address'            => ['nullable', 'string'],
            'addresses.*.email'             => ['nullable', 'string'],
            'addresses.*.alias'             => ['nullable', 'string'],
            'addresses.*.idcountry'         => ['nullable', 'numeric', 'validate_ids_exist:Country'],
            'addresses.*.iddepartment'      => ['nullable', 'numeric', 'validate_ids_exist:Department'],
            'addresses.*.idprovince'        => ['nullable', 'numeric', 'validate_ids_exist:Province'],
            'addresses.*.iddistrict'        => ['nullable', 'numeric', 'validate_ids_exist:District'],
            'addresses.*.idcompany'         => ['nullable', 'numeric', 'validate_ids_exist:Company'],


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

        if ($this->isMethod('POST')) {
            $rules['rut']           = ['required', 'string'];
            $rules['name_rz']       = ['required', 'string'];
            $rules['email']         = ['required', 'string'];
            $rules['phone']         = ['required', 'string'];
            $rules['type']          = ['required', 'numeric', 'min:1', 'max:3'];
            $rules['legal_nature']  = ['required', 'numeric', Rule::in([33, 39])];

            $rules['idwaytopay']    = ['nullable', 'numeric', 'validate_ids_exist:WayToPay'];
            $rules['idsegment']     = ['nullable', 'numeric', 'validate_ids_exist:Segment'];

            // $rules['idcountry']     = ['required', 'numeric', 'validate_ids_exist:Country'];
            // $rules['iddepartment']  = ['required', 'numeric', 'validate_ids_exist:Department'];
            // $rules['idprovince']    = ['required', 'numeric', 'validate_ids_exist:Province'];
            // $rules['iddistrict']    = ['required', 'numeric', 'validate_ids_exist:District'];
            // $rules['address']       = ['required', 'string'];

            $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));
    }
}
