using CMSMicroservice.Protobuf.Protos.AppVersion;
using Google.Protobuf.WellKnownTypes;

namespace BackOffice.Services.AppVersion;

public class AppVersionService : IAppVersionService
{
    private readonly AppVersionContract.AppVersionContractClient _client;

    public AppVersionService(AppVersionContract.AppVersionContractClient client)
    {
        _client = client;
    }

    public async Task<List<AppVersionDto>> GetAllAsync(bool includeInactive = false)
    {
        var request = new GetAllAppVersionsRequest
        {
            IncludeInactive = includeInactive
        };

        var response = await _client.GetAllAppVersionsAsync(request);

        return response.Items.Select(item => new AppVersionDto
        {
            Id = item.Id,
            AppName = item.AppName,
            CurrentVersion = item.CurrentVersion,
            MinRequiredVersion = item.MinRequiredVersion,
            RequiresFullCacheClear = item.RequiresFullCacheClear,
            UpdateMessage = item.UpdateMessage,
            ReleaseNotes = item.ReleaseNotes,
            IsActive = item.IsActive,
            Created = item.Created?.ToDateTime(),
            LastModified = item.LastModified?.ToDateTime()
        }).ToList();
    }

    public async Task<AppVersionDto?> GetByNameAsync(string appName)
    {
        var request = new GetAppVersionRequest
        {
            AppName = appName
        };

        var response = await _client.GetAppVersionAsync(request);

        if (!response.Found)
            return null;

        return new AppVersionDto
        {
            AppName = response.AppName,
            CurrentVersion = response.CurrentVersion,
            MinRequiredVersion = response.MinRequiredVersion,
            RequiresFullCacheClear = response.RequiresFullCacheClear,
            UpdateMessage = response.UpdateMessage,
            ReleaseNotes = response.ReleaseNotes,
            IsActive = true,
            Created = response.LastUpdated?.ToDateTime(),
            LastModified = response.LastUpdated?.ToDateTime()
        };
    }

    public async Task UpdateAsync(UpdateAppVersionDto dto)
    {
        var request = new UpdateAppVersionRequest
        {
            AppName = dto.AppName,
            CurrentVersion = dto.CurrentVersion,
            RequiresFullCacheClear = dto.RequiresFullCacheClear
        };

        if (!string.IsNullOrWhiteSpace(dto.MinRequiredVersion))
            request.MinRequiredVersion = dto.MinRequiredVersion;
        
        if (!string.IsNullOrWhiteSpace(dto.UpdateMessage))
            request.UpdateMessage = dto.UpdateMessage;
        
        if (!string.IsNullOrWhiteSpace(dto.ReleaseNotes))
            request.ReleaseNotes = dto.ReleaseNotes;
        
        if (!string.IsNullOrWhiteSpace(dto.UpdateReason))
            request.UpdateReason = dto.UpdateReason;

        await _client.UpdateAppVersionAsync(request);
    }
}
