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

namespace BackOffice.Services.DiscountProduct;

public class DiscountProductService : IDiscountProductService
{
    private readonly DiscountProductContract.DiscountProductContractClient _client;

    public DiscountProductService(DiscountProductContract.DiscountProductContractClient client)
    {
        _client = client;
    }

    public async Task<(List<DiscountProductDto> Products, int TotalCount, int TotalPages)> GetProductsAsync(ProductFilterDto? filter = null)
    {
        filter ??= new ProductFilterDto();

        var request = new GetDiscountProductsRequest
        {
            PageNumber = filter.PageNumber,
            PageSize = filter.PageSize
        };

        if (!string.IsNullOrEmpty(filter.SearchQuery))
            request.SearchQuery = filter.SearchQuery;
        if (filter.CategoryId.HasValue)
            request.CategoryId = filter.CategoryId.Value;
        if (filter.MinPrice.HasValue)
            request.MinPrice = filter.MinPrice.Value;
        if (filter.MaxPrice.HasValue)
            request.MaxPrice = filter.MaxPrice.Value;
        if (filter.IsActive.HasValue)
            request.IsActive = filter.IsActive.Value;
        if (filter.InStock.HasValue)
            request.InStock = filter.InStock.Value;

        
        var response = await _client.GetDiscountProductsAsync(request);

        
        var products = response.Models.Select(p => new DiscountProductDto
        {
            Id = p.Id,
            Title = p.Title,
            ShortInformation = p.ShortInfomation,
            Price = p.Price,
            MaxDiscountPercent = p.MaxDiscountPercent,
            ImagePath = p.ImagePath,
            ThumbnailPath = p.ThumbnailPath,
            RemainingCount = p.RemainingCount,
            ViewCount = p.ViewCount,
            IsActive = p.IsActive,
            Created = p.Created?.ToDateTime()
        }).ToList();

        var totalCount = (int)(response.MetaData?.TotalCount ?? 0);
        var totalPages = (int)(response.MetaData?.TotalPage ?? 0);

        return (products, totalCount, totalPages);
    }

    public async Task<DiscountProductDetailDto?> GetByIdAsync(long id, long? userId = null)
    {
        var request = new GetDiscountProductByIdRequest 
        { 
            ProductId = id,
            UserId = userId ?? 0
        };
        var response = await _client.GetDiscountProductByIdAsync(request);

        if (response == null || response.Id == 0)
            return null;

        return new DiscountProductDetailDto
        {
            Id = response.Id,
            Title = response.Title,
            ShortInformation = response.ShortInfomation,
            FullInformation = response.FullInformation,
            Price = response.Price,
            MaxDiscountPercent = response.MaxDiscountPercent,
            ImagePath = response.ImagePath,
            ThumbnailPath = response.ThumbnailPath,
            RemainingCount = response.RemainingCount,
            ViewCount = response.ViewCount,
            SortOrder = response.SortOrder,
            IsActive = response.IsActive,
            Categories = response.Categories.Select(c => new CategoryInfoDto
            {
                Id = c.Id,
                Name = c.Name,
                Title = c.Title
            }).ToList(),
            Created = response.Created?.ToDateTime()
        };
    }

    public async Task<long> CreateAsync(CreateDiscountProductDto dto)
    {
        var request = new CreateDiscountProductRequest
        {
            Title = dto.Title,
            ShortInfomation = dto.ShortInformation ?? string.Empty,
            FullInformation = dto.FullInformation ?? string.Empty,
            Price = dto.Price,
            MaxDiscountPercent = dto.MaxDiscountPercent,
            ImagePath = dto.ImagePath ?? string.Empty,
            ThumbnailPath = dto.ThumbnailPath ?? string.Empty,
            InitialCount = dto.InitialCount,
            SortOrder = dto.SortOrder,
            IsActive = dto.IsActive
        };

        if (dto.CategoryIds != null)
        {
            request.CategoryIds.AddRange(dto.CategoryIds);
        }

        // Add image file if provided
        if (dto.ImageFile != null && !string.IsNullOrEmpty(dto.ImageMime) && !string.IsNullOrEmpty(dto.ImageFileName))
        {
            request.ImageFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ImageFile),
                Mime = dto.ImageMime,
                FileName = dto.ImageFileName
            };
        }

        // Add thumbnail file if provided
        if (dto.ThumbnailFile != null && !string.IsNullOrEmpty(dto.ThumbnailMime) && !string.IsNullOrEmpty(dto.ThumbnailFileName))
        {
            request.ThumbnailFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ThumbnailFile),
                Mime = dto.ThumbnailMime,
                FileName = dto.ThumbnailFileName
            };
        }

        var response = await _client.CreateDiscountProductAsync(request);
        return response.ProductId;
    }

    public async Task UpdateAsync(long id, UpdateDiscountProductDto dto)
    {
        var request = new UpdateDiscountProductRequest
        {
            ProductId = id,
            Title = dto.Title,
            ShortInfomation = dto.ShortInformation ?? string.Empty,
            FullInformation = dto.FullInformation ?? string.Empty,
            Price = dto.Price,
            MaxDiscountPercent = dto.MaxDiscountPercent,
            ImagePath = dto.ImagePath ?? string.Empty,
            ThumbnailPath = dto.ThumbnailPath ?? string.Empty,
            SortOrder = dto.SortOrder,
            IsActive = dto.IsActive
        };

        if (dto.CategoryIds != null)
        {
            request.CategoryIds.AddRange(dto.CategoryIds);
        }

        // Handle image file upload
        if (dto.ImageFile != null)
        {
            request.ImageFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ImageFile),
                Mime = dto.ImageMime ?? string.Empty,
                FileName = dto.ImageFileName ?? string.Empty
            };
        }

        // Handle thumbnail file upload
        if (dto.ThumbnailFile != null)
        {
            request.ThumbnailFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ThumbnailFile),
                Mime = dto.ThumbnailMime ?? string.Empty,
                FileName = dto.ThumbnailFileName ?? string.Empty
            };
        }

        // Add image file if provided
        if (dto.ImageFile != null && !string.IsNullOrEmpty(dto.ImageMime) && !string.IsNullOrEmpty(dto.ImageFileName))
        {
            request.ImageFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ImageFile),
                Mime = dto.ImageMime,
                FileName = dto.ImageFileName
            };
        }

        // Add thumbnail file if provided
        if (dto.ThumbnailFile != null && !string.IsNullOrEmpty(dto.ThumbnailMime) && !string.IsNullOrEmpty(dto.ThumbnailFileName))
        {
            request.ThumbnailFile = new ImageFileModel
            {
                File = ByteString.CopyFrom(dto.ThumbnailFile),
                Mime = dto.ThumbnailMime,
                FileName = dto.ThumbnailFileName
            };
        }

        await _client.UpdateDiscountProductAsync(request);
    }

    public async Task DeleteAsync(long id)
    {
        var request = new DeleteDiscountProductRequest { ProductId = id };
        await _client.DeleteDiscountProductAsync(request);
    }
}
