using MediatR;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using TakeoutSaaS.Application.App.Subscriptions.Commands;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Module.Scheduler.Options;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Module.Scheduler.Jobs;

/// <summary>
/// 订阅自动续费任务：为即将到期且开启自动续费的订阅生成续费账单。
/// </summary>
public sealed class SubscriptionAutoRenewalJob(
    IMediator mediator,
    ITenantRepository tenantRepository,
    ITenantContextAccessor tenantContextAccessor,
    IOptionsMonitor<SubscriptionAutomationOptions> optionsMonitor,
    ILogger<SubscriptionAutoRenewalJob> logger)
{
    /// <summary>
    /// 执行自动续费账单生成。
    /// </summary>
    public async Task ExecuteAsync()
    {
        // 1. 读取配置
        var options = optionsMonitor.CurrentValue;

        // 2. (空行后) 获取需要处理的租户列表（排除系统租户）
        var tenants = await tenantRepository.SearchAsync(null, null, CancellationToken.None);
        var targets = tenants.Where(x => x.Id > 0).ToList();

        // 3. (空行后) 按租户逐个执行自动续费
        var candidateCount = 0;
        var createdBillCount = 0;
        var previousContext = tenantContextAccessor.Current;
        try
        {
            foreach (var tenant in targets)
            {
                tenantContextAccessor.Current = new TenantContext(tenant.Id, tenant.Code, "scheduler");
                try
                {
                    var result = await mediator.Send(new ProcessAutoRenewalCommand
                    {
                        RenewalDaysBeforeExpiry = options.AutoRenewalDaysBeforeExpiry
                    });

                    candidateCount += result.CandidateCount;
                    createdBillCount += result.CreatedBillCount;
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "定时任务：自动续费执行失败 TenantId={TenantId}", tenant.Id);
                }
            }
        }
        finally
        {
            tenantContextAccessor.Current = previousContext;
        }

        // 4. (空行后) 记录执行结果
        logger.LogInformation(
            "定时任务：自动续费处理完成，处理租户 {TenantCount}，候选 {CandidateCount}，创建账单 {CreatedBillCount}",
            targets.Count,
            candidateCount,
            createdBillCount);
    }
}
