using JSMR.Application.Integrations.DLSite.Models;
using JSMR.Application.Integrations.DLSite.Models.ReleasedWorks;
using JSMR.Application.Integrations.DLSite.Ports;
using JSMR.Infrastructure.Globalization;
using JSMR.Infrastructure.Http;
using JSMR.Infrastructure.Integrations.DLSite.Mapping;
using JSMR.Infrastructure.Integrations.DLSite.Models;
using JSMR.Infrastructure.Integrations.DLSite.Models.NewWorks;
using Microsoft.Extensions.Logging;

namespace JSMR.Infrastructure.Integrations.DLSite;

public class DLSiteClient(HttpClient http, ILogger<DLSiteClient> logger) : ApiClient(http, logger), IDLSiteClient
{
    public async Task<VoiceWorkDetailCollection> GetVoiceWorkDetailsAsync(string[] productIds, CancellationToken cancellationToken = default)
    {
        string[] validProductIds = [.. productIds.Where(x => !string.IsNullOrWhiteSpace(x)).Distinct()];

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

        string productIdCollection = string.Join(",", validProductIds);
        string url = $"maniax/product/info/ajax?product_id={productIdCollection}&cdn_cache_min=1";

        ProductInfoCollection productInfoCollection = await GetJsonAsync<ProductInfoCollection>(url, cancellationToken: cancellationToken);

        return DLSiteToDomainMapper.Map(productInfoCollection);
    }

    public async Task<ReleasedWorksCollection> GetReleasedWorksAsync(ReleasedWorksRequest request, CancellationToken cancellationToken = default)
    {
        string locale = LocaleMapper.ToDLSiteLocale(request.Locale);
        string date = request.Date.ToString("yyyy-MM-dd");
        string url = $"maniax/new/work/api?locale={locale}&date={date}&period={request.Period}";

        NewWorksApiResponse response = await GetJsonAsync<NewWorksApiResponse>(url, cancellationToken: cancellationToken);

        if (response.Meta.Code != 200)
        {
            throw new InvalidOperationException(
                $"DLsite returned code {response.Meta.Code}. " +
                $"ErrorType: {response.Meta.ErrorType}. " +
                $"ErrorMessage: {response.Meta.ErrorMessage}");
        }

        return DLSiteReleasedWorksMapper.Map(response);
    }
}