using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 更新租户套餐处理器。
/// </summary>
public sealed class UpdateTenantPackageCommandHandler(ITenantPackageRepository packageRepository)
    : IRequestHandler<UpdateTenantPackageCommand, TenantPackageDto?>
{
    /// <inheritdoc />
    public async Task<TenantPackageDto?> Handle(UpdateTenantPackageCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验必填项
        if (string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "套餐名称不能为空");
        }

        // 2. 查询套餐
        var package = await packageRepository.FindByIdAsync(request.TenantPackageId, cancellationToken);
        if (package == null)
        {
            return null;
        }

        // 3. 更新字段
        package.Name = request.Name.Trim();
        package.Description = request.Description;
        package.PackageType = request.PackageType;
        package.MonthlyPrice = request.MonthlyPrice;
        package.YearlyPrice = request.YearlyPrice;
        package.MaxStoreCount = request.MaxStoreCount;
        package.MaxAccountCount = request.MaxAccountCount;
        package.MaxStorageGb = request.MaxStorageGb;
        package.MaxSmsCredits = request.MaxSmsCredits;
        package.MaxDeliveryOrders = request.MaxDeliveryOrders;
        package.FeaturePoliciesJson = request.FeaturePoliciesJson;
        package.IsActive = request.IsActive;
        package.SortOrder = request.SortOrder;

        // 4. 持久化并返回
        await packageRepository.UpdateAsync(package, cancellationToken);
        await packageRepository.SaveChangesAsync(cancellationToken);

        return package.ToDto();
    }
}
