using MediatR;
using Microsoft.Extensions.Logging;
using TakeoutSaaS.Application.App.Deliveries.Commands;
using TakeoutSaaS.Application.App.Deliveries.Dto;
using TakeoutSaaS.Domain.Deliveries.Entities;
using TakeoutSaaS.Domain.Deliveries.Repositories;
using TakeoutSaaS.Domain.Orders.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Deliveries.Handlers;

/// <summary>
/// 更新配送单命令处理器。
/// </summary>
public sealed class UpdateDeliveryOrderCommandHandler(
    IDeliveryRepository deliveryRepository,
    IOrderRepository orderRepository,
    ILogger<UpdateDeliveryOrderCommandHandler> logger)
    : IRequestHandler<UpdateDeliveryOrderCommand, DeliveryOrderDto?>
{
    /// <inheritdoc />
    public async Task<DeliveryOrderDto?> Handle(UpdateDeliveryOrderCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询目标配送单（跨租户）
        var existing = await deliveryRepository.FindByIdAsync(request.DeliveryOrderId, cancellationToken);
        if (existing == null)
        {
            return null;
        }

        // 2. (空行后) 查询订单以确定租户
        var order = await orderRepository.FindByIdAsync(request.OrderId, cancellationToken);
        if (order is null)
        {
            throw new BusinessException(ErrorCodes.NotFound, "订单不存在");
        }

        // 3. (空行后) 更新字段并写入租户
        existing.TenantId = order.TenantId;
        existing.OrderId = request.OrderId;
        existing.Provider = request.Provider;
        existing.ProviderOrderId = request.ProviderOrderId?.Trim();
        existing.Status = request.Status;
        existing.DeliveryFee = request.DeliveryFee;
        existing.CourierName = request.CourierName?.Trim();
        existing.CourierPhone = request.CourierPhone?.Trim();
        existing.DispatchedAt = request.DispatchedAt;
        existing.PickedUpAt = request.PickedUpAt;
        existing.DeliveredAt = request.DeliveredAt;
        existing.FailureReason = request.FailureReason?.Trim();

        // 4. (空行后) 持久化变更
        await deliveryRepository.UpdateDeliveryOrderAsync(existing, cancellationToken);
        await deliveryRepository.SaveChangesAsync(cancellationToken);

        // 5. (空行后) 记录更新日志
        logger.LogInformation("更新配送单 {DeliveryOrderId}", existing.Id);

        // 6. (空行后) 查询事件并返回映射结果
        var events = await deliveryRepository.GetEventsAsync(existing.Id, existing.TenantId, cancellationToken);
        return MapToDto(existing, events);
    }

    private static DeliveryOrderDto MapToDto(DeliveryOrder deliveryOrder, IReadOnlyList<DeliveryEvent> events) => new()
    {
        Id = deliveryOrder.Id,
        TenantId = deliveryOrder.TenantId,
        OrderId = deliveryOrder.OrderId,
        Provider = deliveryOrder.Provider,
        ProviderOrderId = deliveryOrder.ProviderOrderId,
        Status = deliveryOrder.Status,
        DeliveryFee = deliveryOrder.DeliveryFee,
        CourierName = deliveryOrder.CourierName,
        CourierPhone = deliveryOrder.CourierPhone,
        DispatchedAt = deliveryOrder.DispatchedAt,
        PickedUpAt = deliveryOrder.PickedUpAt,
        DeliveredAt = deliveryOrder.DeliveredAt,
        FailureReason = deliveryOrder.FailureReason,
        CreatedAt = deliveryOrder.CreatedAt,
        Events = events.Select(x => new DeliveryEventDto
        {
            Id = x.Id,
            DeliveryOrderId = x.DeliveryOrderId,
            EventType = x.EventType,
            Message = x.Message,
            OccurredAt = x.OccurredAt,
            Payload = x.Payload
        }).ToList()
    };
}
