using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace CMSMicroservice.Application.BlogPostCQ.Commands.PublishBlogPost;

public class PublishBlogPostCommandHandler : IRequestHandler<PublishBlogPostCommand, PublishBlogPostResult>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<PublishBlogPostCommandHandler> _logger;

    public PublishBlogPostCommandHandler(IApplicationDbContext context, ILogger<PublishBlogPostCommandHandler> logger)
    {
        _context = context;
        _logger = logger;
    }

    public async Task<PublishBlogPostResult> Handle(PublishBlogPostCommand request, CancellationToken cancellationToken)
    {
        var post = await _context.BlogPosts.FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken)
            ?? throw new KeyNotFoundException($"مقاله با شناسه {request.Id} یافت نشد");

        if (post.Status == BlogPostStatus.Published)
            return new PublishBlogPostResult { Success = false, Message = "مقاله قبلاً منتشر شده است" };

        post.Status = BlogPostStatus.Published;
        post.PublishedAt = DateTime.UtcNow;
        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation("Blog post published. Id: {Id}, Title: {Title}", post.Id, post.Title);

        return new PublishBlogPostResult
        {
            Success = true,
            Message = "مقاله با موفقیت منتشر شد",
            PublishedAt = post.PublishedAt
        };
    }
}
