<?php

declare(strict_types=1);

namespace Hexspoor\MonitorClient;

use Hexspoor\MonitorClient\Console\Commands\SendLogsToMonitorCommand;
use Hexspoor\MonitorClient\Contracts\ClientContract;
use Hexspoor\MonitorClient\Contracts\LoggerContract;
use Illuminate\Contracts\Config\Repository;
use Illuminate\Contracts\Container\Container;
use Illuminate\Contracts\Support\DeferrableProvider;

final class ServiceProvider extends \Illuminate\Support\ServiceProvider implements DeferrableProvider
{
    public function register()
    {
        $this->app->singleton(ClientContract::class, function (Container $container) {
            /** @var \Illuminate\Contracts\Config\Repository $config */
            $config = $container->make(Repository::class);

            return new Client(
                $config->get('monitor.url'),
                $config->get('monitor.token'),
                (int) $config->get('monitor.system_id')
            );
        });

        $this->app->singleton(LoggerContract::class, function () {
            return new Logger();
        });
    }

    /**
     * Perform post-registration booting of services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/../config/monitor.php' => config_path('monitor.php'),
        ]);

        $this->mergeConfigFrom(__DIR__ . '/../config/monitor.php','monitor');

        $this->loadMigrationsFrom(__DIR__ . '/../database/migrations');

        if ($this->app->runningInConsole()) {
            $this->commands([
                SendLogsToMonitorCommand::class,
            ]);
        }
    }

    public function provides()
    {
        return [ClientContract::class, LoggerContract::class];
    }
}
