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 UpdateSubscriptionCommandHandler(
    ISubscriptionRepository subscriptionRepository,
    IMediator mediator)
    : IRequestHandler<UpdateSubscriptionCommand, SubscriptionDetailDto?>
{
    /// <inheritdoc />
    public async Task<SubscriptionDetailDto?> Handle(UpdateSubscriptionCommand request, CancellationToken cancellationToken)
    {
        // 1. 查询订阅
        var subscription = await subscriptionRepository.FindByIdAsync(
            request.SubscriptionId,
            cancellationToken);

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

        // 2. 更新字段
        if (request.AutoRenew.HasValue)
        {
            subscription.AutoRenew = request.AutoRenew.Value;
        }

        if (request.Notes != null)
        {
            subscription.Notes = request.Notes;
        }

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

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