<?php

namespace App\Http\Requests;

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

class AdminCompanyRequest extends FormRequest
{
    use HasResponse;

    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        $rules = [
            'rut'           => ['required','string','max:11'],
            'name'          => ['required', 'string', 'max:100'],
            'surname'       => ['required', 'string', 'max:100'],
            'email'         => ['required', 'string', 'max:100'],
            'phone'         => ['nullable', 'string', 'max:15'],
            'address'       => ['nullable', 'string', 'max:200'],
            'birthdate'     => ['nullable', 'date'],
            'username'      => ['nullable', 'string', 'max:100'],
            'idcompany'     => ['required', 'numeric', 'validate_ids_exist:Company'],
        ];

        if ($this->isMethod('PATCH')) {
            foreach ($rules as $field => &$rule) {
                if ($field !== 'idcompany') {
                    $rule = array_diff($rule, ['required']);
                    $rule[] = 'nullable';
                }
            }
        }

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