<?php

namespace App\Components\Client;

use App\Models\Claim\Claim;
use App\Models\Client\Client;
use App\Services\ApplicationService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Livewire\Component;

class ClientTabs extends Component {
    use AuthorizesRequests;
    public string $activeTab;

    public Client $client;
    public ?Claim $claim = null;

    protected string $cacheKey;

    public function mount(Client $client): void {
        $this->client = $client;
        $this->claim = $client->claim;

        $this->cacheKey = $this->makeCacheKey();

        $this->activeTab = Cache::remember(
            $this->cacheKey,
            now()->addMonth(),
            fn() => $this->defaultTab()
        );
    }

    public function generateApplication(ApplicationService $service) {
        $this->authorize('claims.application.generate');
        $service->build($this->client);
    }

    protected function makeCacheKey(): string {
        return sprintf(
            'client_tabs.user_%s.client_%s',
            Auth::id() ?? 'guest',
            $this->client->getKey()
        );
    }

    protected function defaultTab(): string {
        return 'overview';
    }

    public function setTab(string $tab): void {
        $this->activeTab = $tab;

        Cache::put(
            $this->cacheKey ?? $this->makeCacheKey(),
            $tab,
            now()->addMonth()
        );

        $this->dispatch('tabLoading');
        $this->dispatch('tabChanged', tab: $tab);
    }

    public function render() {
        return view('components.client.client-tabs');
    }
}
