<?php

namespace Modules\ProductCompat\Providers;

use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Factory;
use Modules\ProductCompat\Entities\PcPartNumber;
use Modules\ProductCompat\Entities\PcDeviceCompat;
use Modules\ProductCompat\Entities\PcCompatible;
use Modules\ProductCompat\Entities\PcProductBarcode;
use Modules\ProductCompat\Entities\PcProductStatus;

class ProductCompatServiceProvider extends ServiceProvider
{
    /**
     * Boot the application events.
     *
     * @return void
     */
    public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->registerModalComposer();
        $this->registerSchedule();
    }

    /**
     * Self-register the auto-enrichment schedule (no Kernel.php edit needed),
     * driven entirely by the UI settings. Only active in console, where the
     * server cron `php artisan schedule:run` evaluates it.
     *
     * @return void
     */
    protected function registerSchedule()
    {
        if (! $this->app->runningInConsole()) {
            return;
        }

        $this->app->booted(function () {
            try {
                if (! Schema::hasTable('pc_settings')) {
                    return;
                }

                $get = fn ($k, $d) => \Modules\ProductCompat\Entities\Services\Settings::get($k, $d);

                if (\Modules\ProductCompat\Entities\Services\Settings::bool('auto_enrich_enabled')) {
                    $target = $get('auto_enrich_target', 'enrich_has');
                    $size   = (int) $get('enrich_batch_size', 400);
                    $freq   = $get('auto_enrich_frequency', 'hourly');
                    $flag   = $target === 'enrich_missing' ? '--missing' : '--has-partnumber';

                    $schedule = $this->app->make(\Illuminate\Console\Scheduling\Schedule::class);
                    $event = $schedule->command("productcompat:enrich {$flag} --skip-enriched --limit={$size} --sleep=80")
                        ->withoutOverlapping()->runInBackground();

                    match ($freq) {
                        'everyFifteenMinutes' => $event->everyFifteenMinutes(),
                        'everyThirtyMinutes'  => $event->everyThirtyMinutes(),
                        'daily'               => $event->daily(),
                        default               => $event->hourly(),
                    };
                }

                // AI search queue worker — drains pc_search_queue review-first.
                if (\Modules\ProductCompat\Entities\Services\Settings::bool('ai_queue_enabled')) {
                    $size = (int) $get('ai_queue_batch_size', 10);
                    $freq = $get('ai_queue_frequency', 'hourly');

                    $schedule = $this->app->make(\Illuminate\Console\Scheduling\Schedule::class);
                    $event = $schedule->command("productcompat:process-queue --scheduled --limit={$size}")
                        ->withoutOverlapping()->runInBackground();

                    match ($freq) {
                        'everyFifteenMinutes' => $event->everyFifteenMinutes(),
                        'everyThirtyMinutes'  => $event->everyThirtyMinutes(),
                        'daily'               => $event->daily(),
                        default               => $event->hourly(),
                    };
                }
            } catch (\Throwable $e) {
                // never break the console over scheduling
            }
        });
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->register(RouteServiceProvider::class);
        $this->registerCommands();
    }

    /**
     * Inject the structured part-number / compatibility data into the product
     * view modal. The live modal is custom_views/product/view-modal.blade.php,
     * which still resolves to the "product.view-modal" view name, so a single
     * composer covers it without touching the core controller.
     *
     * @return void
     */
    protected function registerModalComposer()
    {
        View::composer('product.view-modal', function ($view) {
            $data = $view->getData();
            $product = $data['product'] ?? null;

            // Guard: module may not be migrated yet on a fresh checkout.
            if (empty($product) || ! Schema::hasTable('pc_part_numbers')) {
                return;
            }

            $productId = $product->id;

            $partNumbers = PcPartNumber::where('product_id', $productId)
                ->orderByDesc('is_primary')
                ->orderBy('type')
                ->get();

            $deviceModels = PcDeviceCompat::with('deviceModel')
                ->where('product_id', $productId)
                ->get()
                ->pluck('deviceModel')
                ->filter()
                ->sortBy([['brand', 'asc'], ['series', 'asc'], ['model', 'asc']])
                ->values();

            $compatibles = PcCompatible::with('compatibleProduct')
                ->where('product_id', $productId)
                ->get();

            $status = PcProductStatus::where('product_id', $productId)->first();
            $barcodes = PcProductBarcode::where('product_id', $productId)->get();

            $view->with([
                'pcPartNumbers'  => $partNumbers,
                'pcDeviceModels' => $deviceModels,
                'pcCompatibles'  => $compatibles,
                'pcBarcodes'     => $barcodes,
                'pcStatus'       => $status,
            ]);
        });
    }

    /**
     * Register config.
     *
     * @return void
     */
    protected function registerConfig()
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('productcompat.php'),
        ], 'config');
        $this->mergeConfigFrom(
            __DIR__ . '/../Config/config.php', 'productcompat'
        );
    }

    /**
     * Register views.
     *
     * @return void
     */
    public function registerViews()
    {
        $viewPath = resource_path('views/modules/product-compat');
        $sourcePath = __DIR__ . '/../Resources/views';

        $this->publishes([
            $sourcePath => $viewPath,
        ], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/product-compat';
        }, Config::get('view.paths')), [$sourcePath]), 'productcompat');
    }

    /**
     * Register translations.
     *
     * @return void
     */
    public function registerTranslations()
    {
        $langPath = resource_path('lang/modules/product-compat');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'productcompat');
        } else {
            $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'productcompat');
        }
    }

    /**
     * Register an additional directory of factories.
     *
     * @return void
     */
    public function registerFactories()
    {
        if (! app()->environment('production') && $this->app->runningInConsole()) {
            app(Factory::class)->load(__DIR__ . '/../Database/factories');
        }
    }

    /**
     * Register commands.
     *
     * @return void
     */
    protected function registerCommands()
    {
        $this->commands([
            \Modules\ProductCompat\Console\ParseCustomFields::class,
            \Modules\ProductCompat\Console\EnrichProducts::class,
            \Modules\ProductCompat\Console\ProcessSearchQueue::class,
            \Modules\ProductCompat\Console\ExportProducts::class,
            \Modules\ProductCompat\Console\ExportBatches::class,
            \Modules\ProductCompat\Console\ImportEnrichment::class,
            \Modules\ProductCompat\Console\MatchCompatibility::class,
            \Modules\ProductCompat\Console\Coverage::class,
        ]);
    }

    /**
     * @return array
     */
    public function provides()
    {
        return [];
    }
}
