using System.Collections.Generic;
using CMSMicroservice.Application.AppVersionCQ.Queries.GetAllAppVersions;
using CMSMicroservice.Protobuf.Protos.AppVersion;
using Google.Protobuf.WellKnownTypes;
using Mapster;

namespace CMSMicroservice.WebApi.Common.Mappings;

public class AppVersionProfile : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        // Map List<AppVersionItemDto> to GetAllAppVersionsResponse
        config.NewConfig<List<AppVersionItemDto>, GetAllAppVersionsResponse>()
            .MapWith(src => CreateResponse(src));

        // Map AppVersionItemDto to AppVersionItem (proto message)
        config.NewConfig<AppVersionItemDto, AppVersionItem>()
            .Map(dest => dest.Id, src => src.Id)
            .Map(dest => dest.AppName, src => src.AppName)
            .Map(dest => dest.CurrentVersion, src => src.CurrentVersion)
            .Map(dest => dest.MinRequiredVersion, src => src.MinRequiredVersion ?? string.Empty)
            .Map(dest => dest.RequiresFullCacheClear, src => src.RequiresFullCacheClear)
            .Map(dest => dest.UpdateMessage, src => src.UpdateMessage ?? string.Empty)
            .Map(dest => dest.ReleaseNotes, src => src.ReleaseNotes ?? string.Empty)
            .Map(dest => dest.IsActive, src => src.IsActive)
            .Map(dest => dest.Created, src => Timestamp.FromDateTime(DateTime.SpecifyKind(src.Created, DateTimeKind.Utc)))
            .Map(dest => dest.LastModified, src => src.LastModified.HasValue 
                ? Timestamp.FromDateTime(DateTime.SpecifyKind(src.LastModified.Value, DateTimeKind.Utc)) 
                : null);
    }

    private static GetAllAppVersionsResponse CreateResponse(List<AppVersionItemDto> items)
    {
        var response = new GetAllAppVersionsResponse();
        foreach (var item in items)
        {
            response.Items.Add(item.Adapt<AppVersionItem>());
        }
        return response;
    }
}
