using CMSMicroservice.Application.Common.Interfaces;
using CMSMicroservice.Domain.Enums;
using Microsoft.EntityFrameworkCore;
using ValidationException = FluentValidation.ValidationException;

namespace CMSMicroservice.Application.UserOrderCQ.Commands.UpdateOrderStatus;

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

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

    public async Task<UpdateOrderStatusResponseDto> Handle(UpdateOrderStatusCommand request, CancellationToken cancellationToken)
    {
        var order = await _context.UserOrders
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);

        if (order == null)
        {
            throw new NotFoundException(nameof(order), request.OrderId);
        }

        var oldStatus = order.DeliveryStatus;

        // قوانین ساده انتقال وضعیت: از Cancelled نمی‌توان خارج شد
        if (oldStatus == DeliveryStatus.Cancelled)
        {
            throw new ValidationException("امکان تغییر وضعیت سفارش لغو شده وجود ندارد");
        }

        order.DeliveryStatus = request.NewStatus;

        await _context.SaveChangesAsync(cancellationToken);

        _logger.LogInformation(
            "Order {OrderId} status changed from {OldStatus} to {NewStatus}",
            request.OrderId,
            oldStatus,
            request.NewStatus);

        return new UpdateOrderStatusResponseDto
        {
            Success = true,
            Message = "وضعیت سفارش با موفقیت تغییر کرد",
            CurrentStatus = order.DeliveryStatus
        };
    }
}
