<?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 InternalGuideRequest extends FormRequest
{
    use HasResponse;

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

    public function rules(): array
    {
        $rules = [
            'date'                      => ['required','date'],
            'operation'                 => ['required', 'in:1'],
            'idstore'                   => ['required', 'numeric'],
            'iddocument'                => ['required', 'numeric'],
            'folio'                     => ['required', 'numeric'],
            'idsupplier'                => ['required', 'numeric'],
            'internal_number'           => ['required', 'numeric'],
            'observation'               => ['nullable', 'string'],
            'detail'                    => ['nullable', 'array'],
            'detail.code.*'             => ['required_with:detail', 'string'],
            'detail.detail.*'           => ['required_with:detail', 'string'],
            'detail.count.*'            => ['required_with:detail', 'numeric'],
            'detail.cost.*'             => ['required_with:detail', 'numeric', 'regex:/^\d{1,10}(\.\d{1,2})?$/'],
            'detail.discount_type.*'    => ['required_with:detail', 'in:1,2'],
            'detail.discount_amount.*'  => ['required_with:detail', 'numeric', 'regex:/^\d{1,10}(\.\d{1,2})?$/'],
            'idcompany'                 => ['nullable', 'numeric'],
        ];

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