using System;
using System.Diagnostics;
using Expedience.Infrastructure.Models;

namespace Expedience.Web.Services;

public interface IApiService
{
    public ValueTask<List<DutyCompletionRecord>?> GetDutyCompletionRecordsAsync(string expac, CancellationToken cancellationToken);
    public ValueTask<List<DeepDungeonRecord>?> GetDeepDungeonRecordsAsync(CancellationToken cancellationToken);
}

public class ApiService : IApiService
{
    private ILogger _logger;
    private HttpClient _httpClient { get; }

    public ApiService(ILogger<ApiService> logger, HttpClient httpClient)
    {
        _logger = logger;
        _httpClient = httpClient;
    }

    public async ValueTask<List<DutyCompletionRecord>?> GetDutyCompletionRecordsAsync(string expac, CancellationToken cancellationToken)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            var records = await _httpClient.GetFromJsonAsync<List<DutyCompletionRecord>?>($"/api/DutyCompletionRecords/{expac}", cancellationToken);
            _logger.LogInformation("Retrieved Duty Completion Records in {duration}ms", stopwatch.ElapsedMilliseconds);
            return records;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred trying to retrieve Duty Completion Records for {expac}: {errorMessage}", 
                expac, ex.Message);
        }

        return new List<DutyCompletionRecord>();
    }

    public async ValueTask<List<DeepDungeonRecord>?> GetDeepDungeonRecordsAsync(CancellationToken cancellationToken)
    {
        var stopwatch = Stopwatch.StartNew();
        try
        {
            var records = await _httpClient.GetFromJsonAsync<List<DeepDungeonRecord>?>($"/api/DeepDungeonRecords", cancellationToken);
            _logger.LogInformation("Retrieved Deep Dungeon Records in {duration}ms", stopwatch.ElapsedMilliseconds);
            return records;
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "An error occurred trying to retrieve Deep Dungeon Records: {errorMessage}", ex.Message);
        }

        return new List<DeepDungeonRecord>();
    }
}
