using Newtonsoft.Json;
using UserDtos = OF_DL.Models.Dtos.Users;
using UserEntities = OF_DL.Models.Entities.Users;

namespace OF_DL.Services;

public interface ICajetanApiService : IApiService
{
    Task<UserEntities.UserInfo?> GetDetailedUserInfo(string endpoint);
}

public class CajetanApiService(IAuthService authService, IConfigService configService, ICajetanDbService dbService)
    : ApiService(authService, configService, dbService), ICajetanApiService
{
    public new async Task<UserEntities.User?> GetUserInfo(string endpoint)
    {
        UserEntities.UserInfo? userInfo = await GetDetailedUserInfo(endpoint);

        if (userInfo is not null && !endpoint.EndsWith("/me"))
            await dbService.UpdateUserInfoAsync(userInfo);

        return userInfo;
    }

    /// <summary>
    /// Retrieves detailed user information from the API.
    /// </summary>
    /// <param name="endpoint">The user endpoint.</param>
    /// <returns>The user entity when available.</returns>
    public async Task<UserEntities.UserInfo?> GetDetailedUserInfo(string endpoint)
    {
        Log.Debug($"Calling GetDetailedUserInfo: {endpoint}");

        if (!HasSignedRequestAuth())
            return null;

        try
        {
            UserEntities.UserInfo userInfo = new();
            Dictionary<string, string> getParams = new()
            {
                { "limit", Constants.ApiPageSize.ToString() }, { "order", "publish_date_asc" }
            };

            HttpClient client = new();
            HttpRequestMessage request = await BuildHttpRequestMessage(getParams, endpoint);

            using HttpResponseMessage response = await client.SendAsync(request);

            if (!response.IsSuccessStatusCode)
                return userInfo;

            response.EnsureSuccessStatusCode();
            string body = await response.Content.ReadAsStringAsync();
            UserDtos.UserDto? userDto = JsonConvert.DeserializeObject<UserDtos.UserDto>(body, s_mJsonSerializerSettings);
            userInfo = FromDto(userDto);
            return userInfo;
        }
        catch (Exception ex)
        {
            ExceptionLoggerHelper.LogException(ex);
        }

        return null;
    }

    private static UserEntities.UserInfo FromDto(UserDtos.UserDto? userDto)
    {
        if (userDto is null)
            return new();

        return new()
        {
            Id = userDto.Id,

            Avatar = userDto.Avatar,
            Header = userDto.Header,
            Name = userDto.Name,
            Username = userDto.Username,

            SubscribePrice = userDto.SubscribePrice,
            CurrentSubscribePrice = userDto.CurrentSubscribePrice,
            IsPaywallRequired = userDto.IsPaywallRequired,
            IsRestricted = userDto.IsRestricted,
            SubscribedBy = userDto.SubscribedBy,
            SubscribedByExpire = userDto.SubscribedByExpire,
            SubscribedByExpireDate = userDto.SubscribedByExpireDate,
            SubscribedByAutoprolong = userDto.SubscribedByAutoprolong,
            SubscribedIsExpiredNow = userDto.SubscribedIsExpiredNow,
            SubscribedOn = userDto.SubscribedOn,
            SubscribedOnExpiredNow = userDto.SubscribedOnExpiredNow,
            SubscribedOnDuration = userDto.SubscribedOnDuration,
            About = userDto.About,
            PostsCount = userDto.PostsCount,
            ArchivedPostsCount = userDto.ArchivedPostsCount,
            PrivateArchivedPostsCount = userDto.PrivateArchivedPostsCount,
            PhotosCount = userDto.PhotosCount,
            VideosCount = userDto.VideosCount,
            AudiosCount = userDto.AudiosCount,
            MediasCount = userDto.MediasCount,
        };
    }
}
