<?php

namespace App\Console\Commands;

use App\Jobs\UpdateGoldPriceJob;
use App\Models\Configuration;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class AutoUpdateGoldPrices extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'gold:auto-update-prices {--execution-type=automatic : Execution type: automatic or manual} {--collection= : Specific collection name to process}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Automatically update gold prices for all enabled collections if auto_10k or auto_14k is enabled';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $executionType = $this->option('execution-type');
        $specificCollection = $this->option('collection');

        $this->info("Starting gold price update process...");
        $this->info("Execution type: " . $executionType);
        Log::info('AutoUpdateGoldPrices: Command started', [
            'execution_type' => $executionType,
            'collection_option' => $specificCollection,
        ]);

        // Get configuration
        $config = Configuration::getInstance();

        // Check if auto-update is enabled
        if (!$config->auto_10k && !$config->auto_14k) {
            $this->warn("Auto-update is disabled for both 10k and 14k. Exiting...");
            Log::warning('AutoUpdateGoldPrices: Exiting - auto_10k and auto_14k are both disabled', [
                'auto_10k' => $config->auto_10k,
                'auto_14k' => $config->auto_14k,
            ]);
            return 0;
        }
        Log::info('AutoUpdateGoldPrices: Auto-update enabled', [
            'auto_10k' => $config->auto_10k,
            'auto_14k' => $config->auto_14k,
        ]);

        // Determine which collections to process
        $collectionsToProcess = [];

        if ($specificCollection) {
            // Process specific collection
            $this->info("Processing specific collection: " . $specificCollection);
            $collectionsToProcess = [['name' => $specificCollection, 'enabled' => true]];
        } else {
            // Process all enabled collections from configuration
            $configuredCollections = $config->collections ?? [];
            foreach ($configuredCollections as $collectionConfig) {
                if ($collectionConfig['enabled'] ?? false) {
                    $collectionsToProcess[] = $collectionConfig;
                }
            }

            if (empty($collectionsToProcess)) {
                $this->warn("No enabled collections found in configuration. Exiting...");
                Log::warning('AutoUpdateGoldPrices: Exiting - no enabled collections in config', [
                    'configured_collections_count' => count($configuredCollections ?? []),
                ]);
                return 0;
            }

            $this->info("Found " . count($collectionsToProcess) . " enabled collection(s) to process");
        }

        $collectionNames = array_map(fn($c) => $c['name'], $collectionsToProcess);
        Log::info('AutoUpdateGoldPrices: Collections to process resolved', [
            'count' => count($collectionsToProcess),
            'collection_names' => $collectionNames,
            'specific_collection_passed_to_job' => $specificCollection,
        ]);

        $this->info("Dispatching gold price update job asynchronously...");

        // Dispatch the job to run asynchronously
        // Pass specific collection name if provided, otherwise null to process all enabled collections
        Log::info('AutoUpdateGoldPrices: Dispatching UpdateGoldPriceJob', [
            'execution_type' => $executionType,
            'collection_name_param' => $specificCollection,
        ]);
        UpdateGoldPriceJob::dispatch($executionType, $specificCollection);
        Log::info('AutoUpdateGoldPrices: UpdateGoldPriceJob dispatched successfully');

        $this->info("Job dispatched successfully! Processing will continue in the background.");

        if ($specificCollection) {
            $this->info("Collection to process: " . $specificCollection);
        } else {
            $this->info("Collections to process: " . implode(', ', $collectionNames));
        }

        return 0;
    }
}
