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

namespace CMSMicroservice.Application.DiscountShopCQ.Commands.UpdateOrderStatus;

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

    public UpdateOrderStatusCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

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

        if (order == null)
        {
            return new UpdateOrderStatusResponseDto
            {
                Success = false,
                Message = "سفارش یافت نشد"
            };
        }

        // به‌روزرسانی وضعیت
        order.DeliveryStatus = request.DeliveryStatus;

        if (!string.IsNullOrEmpty(request.TrackingCode))
        {
            order.TrackingCode = request.TrackingCode;
        }

        if (!string.IsNullOrEmpty(request.AdminNotes))
        {
            order.DeliveryDescription = request.AdminNotes;
        }

        await _context.SaveChangesAsync(cancellationToken);

        return new UpdateOrderStatusResponseDto
        {
            Success = true,
            Message = "وضعیت سفارش به‌روزرسانی شد"
        };
    }
}
