using MediatR;
using TakeoutSaaS.Application.App.Subscriptions.Commands;
using TakeoutSaaS.Application.App.Subscriptions.Dto;
using TakeoutSaaS.Application.App.Subscriptions.Queries;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Subscriptions.Handlers;

/// <summary>
/// 更新订阅状态命令处理器。
/// </summary>
public sealed class UpdateSubscriptionStatusCommandHandler(
    ISubscriptionRepository subscriptionRepository,
    IMediator mediator)
    : IRequestHandler<UpdateSubscriptionStatusCommand, SubscriptionDetailDto?>
{
    /// <inheritdoc />
    public async Task<SubscriptionDetailDto?> Handle(UpdateSubscriptionStatusCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询订阅
        var subscription = await subscriptionRepository.FindByIdAsync(
            request.SubscriptionId,
            cancellationToken);

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

        // 2. 更新状态
        subscription.Status = request.Status;

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

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

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