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

namespace CMSMicroservice.Application.BlogPostCQ.Commands.ArchiveBlogPost;

public class ArchiveBlogPostCommandHandler : IRequestHandler<ArchiveBlogPostCommand, ArchiveBlogPostResult>
{
    private readonly IApplicationDbContext _context;
    private readonly ILogger<ArchiveBlogPostCommandHandler> _logger;

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

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

        post.Status = BlogPostStatus.Archived;
        await _context.SaveChangesAsync(cancellationToken);

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

        return new ArchiveBlogPostResult { Success = true, Message = "مقاله آرشیو شد" };
    }
}
