<?php

namespace App\Http\Requests;

use App\Models\Event;
use Illuminate\Foundation\Http\FormRequest;

/**
 * Alta rápida de sede/recinto desde el formulario de evento (JSON).
 */
class StoreCatalogVenueRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', Event::class) ?? false;
    }

    /**
     * @return array<string, mixed>
     */
    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'address_line_1' => ['nullable', 'string', 'max:255'],
            'address_line_2' => ['nullable', 'string', 'max:255'],
            'city' => ['nullable', 'string', 'max:120'],
            'region' => ['nullable', 'string', 'max:120'],
            'postal_code' => ['nullable', 'string', 'max:32'],
            'country' => ['nullable', 'string', 'regex:/^[A-Za-z]{2}$/'],
            'latitude' => ['nullable', 'numeric', 'between:-90,90'],
            'longitude' => ['nullable', 'numeric', 'between:-180,180'],
        ];
    }

    /**
     * @return array<string, string>
     */
    public function messages(): array
    {
        return [
            'country.regex' => __('El país debe ser un código ISO de 2 letras (ej. PR, US).'),
            'latitude.between' => __('La latitud debe estar entre -90 y 90.'),
            'longitude.between' => __('La longitud debe estar entre -180 y 180.'),
        ];
    }

    protected function prepareForValidation(): void
    {
        $c = $this->input('country');
        if ($c === '' || $c === null) {
            $this->merge(['country' => null]);
        } elseif (is_string($c)) {
            $this->merge(['country' => strtoupper(trim($c))]);
        }
    }
}
