<?php

namespace Maestro\Core\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Validator;

class UpdateTableStateRequest extends FormRequest
{
    private const MAX_STATE_BYTES = 51200; // 50KB

    /**
     * Determine if the user is authorized to make this request.
     */
    public function authorize(): bool
    {
        return $this->user() !== null;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
     */
    public function rules(): array
    {
        return [
            'state' => ['required', 'array'],
        ];
    }

    /**
     * Configure the validator instance (max JSON size).
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            $state = $this->input('state');
            if (is_array($state)) {
                $encoded = json_encode($state);
                if ($encoded !== false && strlen($encoded) > self::MAX_STATE_BYTES) {
                    $validator->errors()->add(
                        'state',
                        'The state payload must not exceed ' . (self::MAX_STATE_BYTES / 1024) . ' KB.'
                    );
                }
            }
        });
    }

    /**
     * Get the error messages for 422 responses.
     */
    public function messages(): array
    {
        return [
            'state.required' => 'The state object is required.',
        ];
    }
}
