using MD.PersianDateTime.Standard;

namespace Netina.Core.EntityServices.OrderHandlers;

public class ConfirmOrderStepCommandHandler(IRepositoryWrapper repositoryWrapper, ISmsService smsService) : IRequestHandler<ConfirmOrderStepCommand, bool>
{
    public async Task<bool> Handle(ConfirmOrderStepCommand request, CancellationToken cancellationToken)
    {
        var order = await repositoryWrapper.SetRepository<Order>()
            .TableNoTracking
            .FirstOrDefaultAsync(o => o.Id == request.OrderId, cancellationToken);
        if (order == null)
            throw new AppException("Order not found", ApiResultStatusCode.NotFound);

        order.SetOrderStatus(request.NextOrderStatus);
        if (request.NextOrderStatus == OrderStatus.Processing)
        {
            var customer = await repositoryWrapper.SetRepository<Customer>().TableNoTracking
                .Where(c => c.Id == order.CustomerId)
                .Select(CustomerMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
            if (customer != null)
            {
                await smsService.SendLookUpAsync(customer.PhoneNumber, "customer-submitOrder",
                    (order.TotalPrice/10).ToString("N0"),order.FactorCode,null, $"{customer.FirstName} {customer.LastName}");
            }
        }
        if (request.NextOrderStatus == OrderStatus.Delivered)
        {
            var delivery = await repositoryWrapper.SetRepository<OrderDelivery>()
                .TableNoTracking
                .FirstOrDefaultAsync(od => od.OrderId == order.Id, cancellationToken);
            if (delivery != null)
            {
                if (request.TrackingCode == null || request.TrackingCode.IsNullOrEmpty())
                    throw new AppException("لطفا کد پیگیری ارسال را پر کنید");
                delivery.SetTrackingCode(request.TrackingCode);
                repositoryWrapper.SetRepository<OrderDelivery>()
                    .Update(delivery);
                await repositoryWrapper.SaveChangesAsync(cancellationToken);

            }
            var customer = await repositoryWrapper.SetRepository<Customer>().TableNoTracking
                .Where(c => c.Id == order.CustomerId)
                .Select(CustomerMapper.ProjectToSDto)
                .FirstOrDefaultAsync(cancellationToken);
            if (customer != null)
            {
                await smsService.SendLookUpAsync(customer.PhoneNumber, "customer-deliveryOrder",
                    order.FactorCode, request.TrackingCode,null, PersianDateTime.Today.ToLongDateString(), $"{customer.FirstName} {customer.LastName}");
            }
        }


        repositoryWrapper.SetRepository<Order>()
            .Update(order);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);

        return true;
    }
}