<?php

namespace Gaco\SnapBi\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Config as LaravelConfig;
use Gaco\SnapBi\Helpers\SnapBiHelper;
use Gaco\SnapBi\SnapBi;
use Gaco\SnapBi\Services\Config;

/**
 * Service Provider for SnapBi package
 * 
 * @property \Illuminate\Contracts\Foundation\Application $app
 */
class SnapBiServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Register SnapBi helper function in global namespace
        if (!function_exists('SnapBi')) {
            require __DIR__ . '/../Helpers/functions.php';
        }

        // Auto-register bank configs from Laravel config if available
        $this->registerBankConfigsFromLaravelConfig();
    }

    /**
     * Register any application services.
     */
    public function register(): void
    {
        // Register SnapBi as singleton
        $this->app->singleton(SnapBi::class, function ($app) {
            return new SnapBi();
        });
    }

    /**
     * Auto-register bank configs from Laravel config file
     * 
     * Reads from config('snap_bi.provider') and registers to library Config
     */
    protected function registerBankConfigsFromLaravelConfig(): void
    {
        // Check if Laravel config facade exists
        if (!class_exists(LaravelConfig::class)) {
            return;
        }

        $providers = LaravelConfig::get('snap_bi.provider', []);

        if (empty($providers)) {
            return;
        }

        // Map Laravel config provider names to library bank names (case-insensitive)
        $bankNameMap = [
            'ocbc' => 'ocbc',
            'bca' => 'bca',
            'mandiri' => 'mandiri',
            'cimb' => 'cimb',
        ];

        foreach ($providers as $providerName => $providerConfig) {
            $bankName = strtolower($providerName);

            // Skip if bank not supported
            if (!isset($bankNameMap[$bankName])) {
                continue;
            }

            // Skip if config is empty or missing required fields
            if (empty($providerConfig) || !isset($providerConfig['client_id'])) {
                continue;
            }

            try {
                // Register config to library using Config::for() and register()
                $bankName = $bankNameMap[$bankName];
                $config = Config::for($bankName);
                $config->register($providerConfig);
            } catch (\Exception $e) {
                // Silently fail if config registration fails
                // This allows manual registration if needed
            }
        }
    }
}
