<?php

namespace App\Services\Forecasting;

use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;

/**
 * Flags forecast weeks that fall within ±4 weeks of a known UK fuel
 * duty change. Per the spec calibration override (n=1), the displayed
 * confidence on flagged weeks is halved and the reasoning text says so.
 */
final class DutyChangeDetector
{
    public const int FLAG_RADIUS_WEEKS = 4;

    /**
     * Returns true if the target Monday is within ±4 weeks of any
     * change in `weekly_pump_prices.ulsp_duty_pence`.
     */
    public function isAdjacent(CarbonInterface $targetMonday): bool
    {
        $start = $targetMonday->copy()->subWeeks(self::FLAG_RADIUS_WEEKS)->toDateString();
        $end = $targetMonday->copy()->addWeeks(self::FLAG_RADIUS_WEEKS)->toDateString();

        $rows = DB::table('weekly_pump_prices')
            ->whereBetween('date', [$start, $end])
            ->orderBy('date')
            ->get(['date', 'ulsp_duty_pence']);

        if ($rows->count() < 2) {
            return false;
        }

        $previous = null;
        foreach ($rows as $r) {
            if ($previous !== null && (int) $r->ulsp_duty_pence !== $previous) {
                return true;
            }
            $previous = (int) $r->ulsp_duty_pence;
        }

        return false;
    }
}
