<?php

namespace App\Http\Requests;

use App\Models\RequestBodyDto\ComputerRegisterRequestBody;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

class ComputerRegisterRequest extends FormRequest
{
    /**
     * 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 [
            "name" => "required|string",
            "macAddress" => "required|mac_address",
            "ipAddress" => "required|ip",
            "sideCode" => "required|string|exists:sides,identifier",
            "type" => "required|string",
        ];
    }

    public function getData(): ComputerRegisterRequestBody
    {
        $validatedData = $this->validated();

        return ComputerRegisterRequestBody::createFromPrimitives(
            $validatedData["name"],
            $validatedData["macAddress"],
            $validatedData["ipAddress"],
            $validatedData["sideCode"],
            $validatedData["type"],
        );
    }

    public function messages(): array {
        return [
            "name.required" => "Computer name is required.",
            "macAddress.required" => "MAC address is required.",
            "macAddress.mac_address" => "MAC address value is not valid.",
            "ipAddress.required" => "IP address is required.",
            "ipAddress.ip" => "IP address value is not valid.",
            "sideCode.required" => "Side Code is required.",
            "sideCode.exists" => "Side (Library) Doesn't exist.",
            "type.required" => "Computer type value is required.",
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            "error" => "Error en la validación",
            "messages" => $validator->errors()
        ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
    }
}
