<?php

namespace App\Console\Commands;

use App\Services\BrentPriceFetcher;
use App\Services\BrentPriceSources\BrentPriceFetchException;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

#[Signature('oil:fetch')]
#[Description('Fetch latest Brent crude prices (EIA primary, FRED fallback)')]
class FetchOilPrices extends Command
{
    public function handle(BrentPriceFetcher $fetcher): int
    {
        try {
            $fetcher->fetchFromEia();
            $this->info('Fetched Brent prices from EIA.');

            return self::SUCCESS;
        } catch (BrentPriceFetchException $e) {
            Log::warning('FetchOilPrices: EIA fetch failed, falling back to FRED', ['error' => $e->getMessage()]);
            $this->warn('EIA fetch failed: '.$e->getMessage().'. Trying FRED...');
        }

        try {
            $fetcher->fetchFromFred();
            $this->info('Fetched Brent prices from FRED.');

            return self::SUCCESS;
        } catch (BrentPriceFetchException $e) {
            Log::error('FetchOilPrices: both EIA and FRED failed', ['error' => $e->getMessage()]);
            $this->error('Both EIA and FRED failed: '.$e->getMessage());

            return self::FAILURE;
        }
    }
}
