namespace BackOffice.Services.Blog;

public class BlogPostImageService : IBlogPostImageService
{
    private readonly CMSMicroservice.Protobuf.Protos.BlogPostImage.BlogPostImageContract.BlogPostImageContractClient _client;

    public BlogPostImageService(
        CMSMicroservice.Protobuf.Protos.BlogPostImage.BlogPostImageContract.BlogPostImageContractClient client)
    {
        _client = client;
    }

    public async Task<List<BlogPostImageItemDto>> GetByPostIdAsync(long blogPostId)
    {
        var response = await _client.GetBlogPostImagesAsync(
            new CMSMicroservice.Protobuf.Protos.BlogPostImage.GetBlogPostImagesRequest
            {
                BlogPostId = blogPostId
            });

        return response.Images.Select(m => new BlogPostImageItemDto
        {
            Id = m.Id,
            BlogPostId = m.BlogPostId,
            ImagePath = m.ImagePath,
            ThumbnailPath = m.ThumbnailPath,
            AltText = m.AltText,
            Caption = m.Caption,
            SortOrder = m.SortOrder
        }).ToList();
    }

    public async Task<long> AddAsync(BlogPostImageAddDto dto)
    {
        var request = new CMSMicroservice.Protobuf.Protos.BlogPostImage.AddBlogPostImageRequest
        {
            BlogPostId = dto.BlogPostId,
            ImagePath = dto.ImagePath,
            ThumbnailPath = dto.ThumbnailPath,
            AltText = dto.AltText ?? string.Empty,
            Caption = dto.Caption ?? string.Empty,
            SortOrder = dto.SortOrder
        };

        var response = await _client.AddBlogPostImageAsync(request);
        return response.Id;
    }

    public async Task DeleteAsync(long id)
    {
        await _client.DeleteBlogPostImageAsync(
            new CMSMicroservice.Protobuf.Protos.BlogPostImage.DeleteBlogPostImageRequest { Id = id });
    }

    public async Task ReorderAsync(List<ImageSortItemDto> items)
    {
        var request = new CMSMicroservice.Protobuf.Protos.BlogPostImage.ReorderBlogPostImagesRequest();

        foreach (var item in items)
        {
            request.Items.Add(new CMSMicroservice.Protobuf.Protos.BlogPostImage.ImageSortItem
            {
                Id = item.Id,
                SortOrder = item.SortOrder
            });
        }

        await _client.ReorderBlogPostImagesAsync(request);
    }
}
