<?php

namespace App\Http\Requests;

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

class InitTerminalSessionRequest 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 [
            "personIdentifier" => "required|string",
            "localTime" => "required|string|date_format:Y-m-d\TH:i:s\Z",
            "macAddress" => "required|mac_address|exists:computers,mac_address",
            "pin" => "required|string",
        ];
    }

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

        return InitTerminalSessionRequestBody::createFromPrimitives(
            $validatedData["personIdentifier"],
            $validatedData["macAddress"],
            $validatedData["localTime"],
            $validatedData["pin"]
        );
    }

    public function messages(): array {
        return [
            "personIdentifier.required" => "Person Identifier is required.",
            "localTime.date_format" => "Local Time format is incorrect.",
            "macAddress.required" => "Computer identifier is required.",
            "macAddress.mac_address" => "Computer identifier format is incorrect.",
            "macAddress.exists" => "Computer doesn't exist.",
            "localTime.required" => "Local Time is required.",
            "pin.required" => "PIN 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));
    }
}
