<?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 IntakeCartRequest 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
    {
        return [
            'idsupplier' => ['nullable', 'integer', 'validate_ids_exist:Supplier'],
            'idcompany'  => ['required', 'integer', 'validate_ids_exist:Company'],
            'idproduct'  => ['required', 'integer', 'validate_ids_exist:Product'],
            'quantity'   => ['nullable', 'numeric']
        ];
    }

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

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