<?php

namespace Khatfield\Tautulli\Providers;

use GuzzleHttp\Client;
use Illuminate\Support\ServiceProvider;
use Khatfield\Tautulli\TautulliClient;

class TautulliServiceProvider extends ServiceProvider
{
    /**
     * Register bindings in the container.
     */
    public function register(): void
    {
        // Merge package config so users only need to publish what they want to override.
        $this->mergeConfigFrom(
            __DIR__ . '/../config/tautulli.php',
            'tautulli',
        );

        // Bind the Guzzle client used specifically for Tautulli.
        $this->app->bind('tautulli.http', function ($app) {
            $cfg = $app['config']['tautulli'];

            return new Client(array_merge(
                $cfg['guzzle'] ?? [],
                [
                    // Base URI is intentionally NOT set here; TautulliClient
                    // builds the full endpoint URL itself so the path is explicit.
                    'headers' => [
                        'Accept' => 'application/json',
                    ],
                ],
            ));
        });

        // Bind the main TautulliClient as a singleton.
        $this->app->singleton(TautulliClient::class, function ($app) {
            $cfg      = $app['config']['tautulli'];
            $httpRoot = trim($cfg['http_root'] ?? '', '/');
            $apiPath  = $httpRoot ? "/{$httpRoot}/api/v2" : '/api/v2';
            $endpoint = rtrim($cfg['url'], '/') . $apiPath;

            return new TautulliClient(
                $app->make('tautulli.http'),
                $endpoint,
                $cfg['api_key'] ?? '',
            );
        });

        // Convenient short alias so facades and helpers can resolve 'tautulli'.
        $this->app->alias(TautulliClient::class, 'tautulli');
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        if ($this->app->runningInConsole()) {
            // php artisan vendor:publish --tag=tautulli-config
            $this->publishes([
                __DIR__ . '/../config/tautulli.php' => config_path('tautulli.php'),
            ], 'tautulli-config');
        }
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array<int, string>
     */
    public function provides(): array
    {
        return [
            TautulliClient::class,
            'tautulli',
            'tautulli.http',
        ];
    }
}
