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

namespace CMSMicroservice.Application.PublicMessageCQ.Commands.DeletePublicMessage;

public class DeletePublicMessageCommandHandler : IRequestHandler<DeletePublicMessageCommand, Unit>
{
    private readonly IApplicationDbContext _context;
    private readonly ICurrentUserService _currentUser;
    private readonly ILogger<DeletePublicMessageCommandHandler> _logger;

    public DeletePublicMessageCommandHandler(
        IApplicationDbContext context,
        ICurrentUserService currentUser,
        ILogger<DeletePublicMessageCommandHandler> logger)
    {
        _context = context;
        _currentUser = currentUser;
        _logger = logger;
    }

    public async Task<Unit> Handle(DeletePublicMessageCommand request, CancellationToken cancellationToken)
    {
        // 1. بررسی Admin
        var currentUserId = _currentUser.UserId;
        if (string.IsNullOrEmpty(currentUserId))
        {
            throw new UnauthorizedAccessException("کاربر احراز هویت نشده است");
        }

        if (!long.TryParse(currentUserId, out var userId))
        {
            throw new UnauthorizedAccessException("شناسه کاربر نامعتبر است");
        }

        // 2. بررسی وجود پیام
        var message = await _context.PublicMessages
            .FirstOrDefaultAsync(x => x.Id == request.Id && !x.IsDeleted, cancellationToken);

        if (message == null)
        {
            throw new KeyNotFoundException($"پیام با شناسه {request.Id} یافت نشد");
        }

        // 3. Soft Delete
        message.IsDeleted = true;

        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation(
            "Public message deleted successfully. Id: {Id}, DeletedBy: {DeletedBy}",
            message.Id,
            userId
        );

        return Unit.Value;
    }
}
