<?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;

#[Signature('oil:backfill {--from=2018-01-01 : ISO start date (inclusive)} {--to= : ISO end date (defaults to today, inclusive)}')]
#[Description('One-shot backfill of historical Brent crude prices from FRED into brent_prices.')]
class BackfillOilPrices extends Command
{
    public function handle(BrentPriceFetcher $fetcher): int
    {
        $from = (string) $this->option('from');
        $to = (string) ($this->option('to') ?: now()->toDateString());

        $this->info("Backfilling Brent ({$from} → {$to}) from FRED...");

        try {
            $count = $fetcher->backfillFromFred($from, $to);
            $this->info(sprintf('Upserted %d Brent rows.', $count));

            return self::SUCCESS;
        } catch (BrentPriceFetchException $e) {
            $this->error('FRED backfill failed: '.$e->getMessage());

            return self::FAILURE;
        }
    }
}
