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

namespace CMSMicroservice.Application.OrderManagementCQ.Commands.UpdateOrderStatus;

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

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

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

        var order = await _context.UserOrders
            .FirstOrDefaultAsync(x => x.Id == request.OrderId && !x.IsDeleted, cancellationToken);

        if (order == null)
        {
            throw new KeyNotFoundException($"سفارش با شناسه {request.OrderId} یافت نشد");
        }

        var oldStatus = order.DeliveryStatus;
        
        order.DeliveryStatus = request.NewStatus;
        
        if (!string.IsNullOrEmpty(request.TrackingCode))
        {
            order.TrackingCode = request.TrackingCode.Trim();
        }
        
        if (!string.IsNullOrEmpty(request.Description))
        {
            order.DeliveryDescription = request.Description.Trim();
        }

        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation(
            "Order status updated by admin. OrderId: {OrderId}, OldStatus: {OldStatus}, NewStatus: {NewStatus}, Admin: {AdminId}",
            order.Id,
            oldStatus,
            request.NewStatus,
            _currentUser.UserId
        );

        return Unit.Value;
    }
}
