<?php

namespace App\Services\Forecasting\Features;

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

/**
 * ΔULSP at lag L: the change in petrol price that ended L weeks before
 * the most recent observation, in pence × 100.
 *
 * lag=0 → ULSP[t-7d] − ULSP[t-14d]   (1-week momentum)
 * lag=1 → ULSP[t-14d] − ULSP[t-21d]  (2-week momentum)
 * lag=3 → ULSP[t-28d] − ULSP[t-35d]  (4-week momentum)
 *
 * Source dates are always strictly before the target Monday — the
 * earliest is target − 7×(lag+1), the older is target − 7×(lag+2).
 */
final class DeltaUlspLag implements ForecastFeature
{
    public function __construct(
        private readonly WeeklyPumpPriceLoader $loader,
        public readonly int $lag,
    ) {}

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

    public function valueFor(CarbonInterface $targetMonday): ?float
    {
        [$newer, $older] = $this->dates($targetMonday);
        $a = $this->loader->ulspPence($newer->toDateString());
        $b = $this->loader->ulspPence($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)),
        ];
    }
}
