<?php

namespace App\Livewire\LicenseTokens;

use App\Models\Clients\Client;
use App\Models\Products\LicenseToken;
use Livewire\Component;
use Livewire\WithPagination;

class Edit extends Component
{
    use WithPagination;

    public LicenseToken $licenseToken;
    public ?int $client_id = null;
    public ?string $name = null;
    public string $token = '';
    public bool $active = false;
    public ?string $mode = null;
    public ?int $rate_limit_per_minute = null;
    public ?string $start_at = null;
    public ?string $end_at = null;
    public ?string $metadata = null;
    public ?string $observation = null;
    public string $clientSearchQuery = '';

    protected $paginationTheme = 'tailwind';

    public function mount(LicenseToken $license_token)
    {
        $this->licenseToken = $license_token;
        $this->client_id = $license_token->client_id ?? null;
        $this->name = $license_token->name;
        $this->token = $license_token->token ?? '';
        $this->active = $license_token->active ?? false;
        $this->mode = $license_token->mode;
        $this->rate_limit_per_minute = $license_token->rate_limit_per_minute;
        $this->start_at = $license_token->start_at ? $license_token->start_at->format('Y-m-d') : null;
        $this->end_at = $license_token->end_at ? $license_token->end_at->format('Y-m-d') : null;
        $this->metadata = $license_token->metadata ? json_encode($license_token->metadata, JSON_PRETTY_PRINT) : null;
        $this->observation = $license_token->observation;
    }

    public function updatedClientSearchQuery()
    {
        // Resetear paginación cuando cambia la búsqueda
        $this->resetPage();
    }

    public function getClientsProperty()
    {
        $query = Client::query();

        if (!empty($this->clientSearchQuery)) {
            $query->where(function($q) {
                $q->where('name', 'like', '%' . $this->clientSearchQuery . '%')
                  ->orWhere('shortname', 'like', '%' . $this->clientSearchQuery . '%');
            });
        }

        return $query->orderBy('name')->paginate(10);
    }

    protected function rules()
    {
        return [
            'client_id' => 'required|exists:clients,id',
            'name' => 'nullable|string|max:255',
            'token' => 'required|string|max:100|unique:license_tokens,token,' . $this->licenseToken->id,
            'active' => 'nullable|boolean',
            'start_at' => 'nullable|date',
            'end_at' => 'nullable|date|after_or_equal:start_at',
            'mode' => 'nullable|string|max:50',
            'rate_limit_per_minute' => 'nullable|integer|min:1',
            'metadata' => 'nullable|string',
            'observation' => 'nullable|string',
        ];
    }

    public function generateToken(): void
    {
        // El formato del token es contrato con el plugin y vive en un solo sitio
        // (MGR-022). Aquí se excluye la propia licencia: su token actual no cuenta
        // como choque al regenerarlo.
        $this->token = LicenseToken::generarToken(exceptoId: $this->licenseToken->id);
    }

    public function update()
    {
        $this->authorize('admin.license-tokens.edit');

        $validated = $this->validate();
        $validated['active'] = $this->active;

        // Procesar metadata JSON
        if (!empty($validated['metadata'])) {
            $decoded = json_decode($validated['metadata'], true);
            $validated['metadata'] = json_last_error() === JSON_ERROR_NONE ? $decoded : null;
        } else {
            $validated['metadata'] = null;
        }

        $this->licenseToken->update($validated);

        session()->flash('success', 'Token actualizado correctamente.');

        return $this->redirect(route('license_tokens.show', $this->licenseToken), navigate: true);
    }

    public function render()
    {
        return view('livewire.license-tokens.edit')
            ->layout('layouts.app');
    }
}

