using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Domain.Orders.Enums;
using TakeoutSaaS.Domain.Orders.Repositories;
using TakeoutSaaS.Module.Scheduler.Options;

namespace TakeoutSaaS.Module.Scheduler.Jobs;

/// <summary>
/// 订单超时 SMS 告警任务。
/// </summary>
public sealed class OrderEscalationJob(
    IOrderRepository orderRepository,
    IOptionsMonitor<OrderTimeoutOptions> options,
    ILogger<OrderEscalationJob> logger)
{
    /// <summary>
    /// 执行超时告警检查。
    /// </summary>
    public async Task ExecuteAsync()
    {
        var config = options.CurrentValue;
        var cutoff = DateTime.UtcNow.AddMinutes(-config.SmsEscalationMinutes);

        // 1. 查询超时待接单订单
        var pendingOrders = await orderRepository.SearchAsync(
            tenantId: 0,
            status: OrderStatus.AwaitingPreparation,
            paymentStatus: null);

        var escalationOrders = pendingOrders
            .Where(o => o.CreatedAt < cutoff)
            .ToList();

        if (escalationOrders.Count == 0)
        {
            logger.LogDebug("无需告警的超时订单");
            return;
        }

        // 2. 逐笔发送告警（SMS 模块后续接入）
        foreach (var order in escalationOrders)
        {
            // TODO: 接入 ISmsSenderResolver 发送短信给店长
            // TODO: 使用 Redis key order:escalation:{orderId} 防重复发送
            logger.LogWarning(
                "订单 {OrderNo} ({OrderId}) 超过 {Minutes} 分钟未接单，需告警",
                order.OrderNo, order.Id, config.SmsEscalationMinutes);
        }
    }
}
