using JSMR.Application.Enums;
using JSMR.Application.Integrations.DLSite.Models.ReleasedWorks;
using JSMR.Application.Integrations.DLSite.Ports;
using JSMR.Application.Scanning.Contracts;
using JSMR.Application.Scanning.Ports;

namespace JSMR.Infrastructure.Scanning;

public class ReleasedWorksProvider(IDLSiteClient dlsiteClient) : IReleasedWorksProvider
{
    public async Task<ReleasedWorksCollection> GetReleasedWorksAsync(VoiceWorkScanResult scanResult, CancellationToken cancellationToken)
    {
        DateOnly[] salesDates =
        [
            .. scanResult.Works
                .Where(x => x.SalesDate.HasValue)
                .Select(x => x.SalesDate!.Value)
        ];

        if (salesDates.Length == 0)
            return [];

        DateOnly minDate = salesDates.Min();
        DateOnly maxDate = salesDates.Max();

        DateOnly requestDate = minDate.AddDays(-1);
        DateOnly requestEndDate = maxDate.AddDays(1);

        int period = (requestEndDate.DayNumber - requestDate.DayNumber) + 1;

        ReleasedWorksRequest releasedWorksRequest = new(
            Locale: Locale.English,
            Date: requestEndDate,
            Period: period
        );

        return await dlsiteClient.GetReleasedWorksAsync(releasedWorksRequest, cancellationToken);
    }
}