<?php

namespace App\Http\Requests;

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

class StoreClienteRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Cliente::class);
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'nombre' => is_string($this->input('nombre')) ? trim($this->input('nombre')) : $this->input('nombre'),
            'email' => $this->filled('email') ? trim((string) $this->input('email')) : null,
            'telefono' => $this->filled('telefono') ? trim((string) $this->input('telefono')) : null,
            'direccion' => $this->filled('direccion') ? trim((string) $this->input('direccion')) : null,
        ]);
    }

    public function rules(): array
    {
        return [
            'nombre' => ['required', 'string', 'max:255'],
            'email' => ['nullable', 'string', 'email:rfc', 'max:255'],
            'telefono' => ['nullable', 'string', 'max:50', 'regex:/^[\d\+\-\s\(\)\.]{7,50}$/'],
            'direccion' => ['nullable', 'string'],
            'cliente_categoria_id' => ['nullable', 'integer', 'exists:cliente_categorias,id'],
        ];
    }
}
