<?php

namespace App\Http\Requests;

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

abstract class ApiFormRequest extends FormRequest
{
    public function validationData(): array
    {
        $json = json_decode($this->getContent() ?: '', true);
        $json = is_array($json) ? $json : [];

        return array_merge(
            $this->query->all(),
            $this->request->all(),
            $this->json()->all(),
            $json
        );
    }

    protected function prepareForValidation(): void
    {
        $json = json_decode($this->getContent() ?: '', true);
        if (is_array($json)) {
            $this->merge($json);
        } else {
            $this->merge($this->json()->all());
        }
    }

    protected function failedValidation(Validator $validator): void
    {
        throw new HttpResponseException(
            response()->json([
                'message' => 'Validation failed.',
                'errors' => $validator->errors(),
            ], 422)
        );
    }
}
