using MediatR;
using TakeoutSaaS.Application.App.Subscriptions.Commands;
using TakeoutSaaS.Application.App.Subscriptions.Dto;
using TakeoutSaaS.Application.App.Subscriptions.Queries;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Ids;

namespace TakeoutSaaS.Application.App.Subscriptions.Handlers;

/// <summary>
/// 变更套餐命令处理器。
/// </summary>
public sealed class ChangeSubscriptionPlanCommandHandler(
    ISubscriptionRepository subscriptionRepository,
    IIdGenerator idGenerator,
    IMediator mediator)
    : IRequestHandler<ChangeSubscriptionPlanCommand, SubscriptionDetailDto?>
{
    /// <inheritdoc />
    public async Task<SubscriptionDetailDto?> Handle(ChangeSubscriptionPlanCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询订阅
        var subscription = await subscriptionRepository.FindByIdAsync(
            request.SubscriptionId,
            cancellationToken);

        if (subscription == null)
        {
            return null;
        }

        // 2. 记录原套餐ID
        var previousPackageId = subscription.TenantPackageId;

        // 3. 根据是否立即生效更新订阅
        if (request.Immediate)
        {
            // 立即生效：直接更新当前套餐
            subscription.TenantPackageId = request.TargetPackageId;
            subscription.ScheduledPackageId = null;
        }
        else
        {
            // 下周期生效：设置排期套餐
            subscription.ScheduledPackageId = request.TargetPackageId;
        }

        // 4. 更新备注
        if (!string.IsNullOrWhiteSpace(request.Notes))
        {
            subscription.Notes = request.Notes;
        }

        // 5. 判断变更类型（升级或降级）
        var fromPackage = await subscriptionRepository.FindPackageByIdAsync(previousPackageId, cancellationToken);
        var toPackage = await subscriptionRepository.FindPackageByIdAsync(request.TargetPackageId, cancellationToken);

        var changeType = SubscriptionChangeType.Upgrade;
        if (fromPackage != null && toPackage != null)
        {
            // 简单根据价格判断升降级
            if (toPackage.MonthlyPrice < fromPackage.MonthlyPrice)
            {
                changeType = SubscriptionChangeType.Downgrade;
            }
        }

        // 6. 记录变更历史
        var history = new TenantSubscriptionHistory
        {
            Id = idGenerator.NextId(),
            TenantId = subscription.TenantId,
            TenantSubscriptionId = subscription.Id,
            FromPackageId = previousPackageId,
            ToPackageId = request.TargetPackageId,
            ChangeType = changeType,
            EffectiveFrom = request.Immediate ? DateTime.UtcNow : subscription.EffectiveTo,
            EffectiveTo = subscription.EffectiveTo,
            Amount = null,
            Currency = null,
            Notes = request.Notes ?? (request.Immediate ? "套餐立即变更" : "套餐排期变更")
        };

        await subscriptionRepository.AddHistoryAsync(history, cancellationToken);

        // 7. 保存更改
        await subscriptionRepository.UpdateAsync(subscription, cancellationToken);
        await subscriptionRepository.SaveChangesAsync(cancellationToken);

        // 8. 返回更新后的详情
        return await mediator.Send(new GetSubscriptionDetailQuery { SubscriptionId = subscription.Id }, cancellationToken);
    }
}
