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

namespace CMSMicroservice.Application.PublicMessageCQ.Commands.UpdatePublicMessage;

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

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

    public async Task<Unit> Handle(UpdatePublicMessageCommand 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. به‌روزرسانی پیام
        message.Title = request.Title.Trim();
        message.Content = request.Content.Trim();
        message.Type = request.Type;
        message.Priority = request.Priority;
        message.IsActive = request.IsActive;
        message.StartsAt = request.StartsAt;
        message.ExpiresAt = request.ExpiresAt;
        message.LinkUrl = request.LinkUrl?.Trim();
        message.LinkText = request.LinkText?.Trim();

        await _context.SaveChangesAsync(cancellationToken);

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

        return Unit.Value;
    }
}
