using JSMR.Application.Scanning.Contracts;

namespace JSMR.Infrastructure.Scanning.Extensions;

public static class DLSiteWorkExtensions
{
    public static void InferAndUpdateExpectedDates(this DLSiteWork[] works)
    {
        // Precompute nearest known effective date on the left and right for each index.
        var left = new DateOnly?[works.Length];
        var right = new DateOnly?[works.Length];

        DateOnly? last = null;
        for (int i = 0; i < works.Length; i++)
        {
            var effective = GetEffectiveDate(works[i]);
            if (effective.HasValue)
                last = effective;

            left[i] = last;
        }

        DateOnly? next = null;
        for (int i = works.Length - 1; i >= 0; i--)
        {
            var effective = GetEffectiveDate(works[i]);
            if (effective.HasValue)
                next = effective;

            right[i] = next;
        }

        // Fill only when BOTH sides exist and match.
        for (int i = 0; i < works.Length; i++)
        {
            DLSiteWork work = works[i];

            if (work.SalesDate.HasValue || work.ExpectedDate.HasValue)
                continue;

            DateOnly? previous = (i > 0) ? left[i - 1] : null;
            DateOnly? nxt = (i < works.Length - 1) ? right[i + 1] : null;

            if (previous.HasValue && nxt.HasValue && previous.Value == nxt.Value)
                work.ExpectedDate = previous.Value;
        }
    }

    private static DateOnly? GetEffectiveDate(DLSiteWork work)
    {
        if (work.ExpectedDate.HasValue)
            return work.ExpectedDate.Value;

        if (!work.SalesDate.HasValue)
            return null;

        // Bucket sales day to Early/Middle/Late => 1/11/21
        var d = work.SalesDate.Value;
        int day = d.Day >= 21 ? 21 : d.Day >= 11 ? 11 : 1;
        return new DateOnly(d.Year, d.Month, day);
    }
}