<?php

namespace App\Services\Forecasting\Features;

use App\Services\Forecasting\Contracts\ForecastFeature;
use App\Services\Forecasting\WeeklyPumpPriceLoader;
use Carbon\CarbonInterface;

/**
 * ΔULSD at lag L. Cross-fuel signal — diesel often leads/lags petrol
 * during oil shocks. Same lag semantics as DeltaUlspLag.
 */
final class DeltaUlsdLag implements ForecastFeature
{
    public function __construct(
        private readonly WeeklyPumpPriceLoader $loader,
        public readonly int $lag,
    ) {}

    public function name(): string
    {
        return 'delta_ulsd_lag_'.$this->lag;
    }

    public function valueFor(CarbonInterface $targetMonday): ?float
    {
        [$newer, $older] = $this->dates($targetMonday);
        $a = $this->loader->ulsdPence($newer->toDateString());
        $b = $this->loader->ulsdPence($older->toDateString());
        if ($a === null || $b === null) {
            return null;
        }

        return (float) ($a - $b);
    }

    public function sourceDates(CarbonInterface $targetMonday): array
    {
        return $this->dates($targetMonday);
    }

    /** @return array{0: CarbonInterface, 1: CarbonInterface} */
    private function dates(CarbonInterface $targetMonday): array
    {
        return [
            $targetMonday->copy()->subDays(7 * ($this->lag + 1)),
            $targetMonday->copy()->subDays(7 * ($this->lag + 2)),
        ];
    }
}
