<?php

namespace App\Services\Forecasting;

use Illuminate\Support\Facades\DB;

/**
 * Loads `weekly_pump_prices` once into an in-memory map keyed by date.
 *
 * Used by features and the ridge model — avoids one SELECT per
 * (week × feature) lookup. Lazy: nothing loads until first query.
 */
final class WeeklyPumpPriceLoader
{
    /** @var array<string, object{date: string, ulsp_pence: int, ulsd_pence: int}>|null */
    private ?array $byDate = null;

    public function ulspPence(string $date): ?int
    {
        $row = $this->byDate()[$date] ?? null;

        return $row === null ? null : (int) $row->ulsp_pence;
    }

    public function ulsdPence(string $date): ?int
    {
        $row = $this->byDate()[$date] ?? null;

        return $row === null ? null : (int) $row->ulsd_pence;
    }

    /** @return array<int, string> Sorted ascending. */
    public function allDates(): array
    {
        return array_keys($this->byDate());
    }

    /** @return array<string, object{date: string, ulsp_pence: int, ulsd_pence: int}> */
    private function byDate(): array
    {
        if ($this->byDate !== null) {
            return $this->byDate;
        }

        $rows = DB::table('weekly_pump_prices')
            ->orderBy('date')
            ->get(['date', 'ulsp_pence', 'ulsd_pence']);

        $map = [];
        foreach ($rows as $r) {
            $map[(string) $r->date] = $r;
        }

        $this->byDate = $map;

        return $map;
    }
}
