using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.App.Tenants.Dto;
using TakeoutSaaS.Domain.Tenants.Entities;
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 CreateTenantPackageCommandHandler(ITenantPackageRepository packageRepository)
    : IRequestHandler<CreateTenantPackageCommand, TenantPackageDto>
{
    /// <inheritdoc />
    public async Task<TenantPackageDto> Handle(CreateTenantPackageCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验套餐名称
        if (string.IsNullOrWhiteSpace(request.Name))
        {
            throw new BusinessException(ErrorCodes.BadRequest, "套餐名称不能为空");
        }

        // 2. 构建套餐实体
        var package = new TenantPackage
        {
            Name = request.Name.Trim(),
            Description = request.Description,
            PackageType = request.PackageType,
            MonthlyPrice = request.MonthlyPrice,
            YearlyPrice = request.YearlyPrice,
            MaxStoreCount = request.MaxStoreCount,
            MaxAccountCount = request.MaxAccountCount,
            MaxStorageGb = request.MaxStorageGb,
            MaxSmsCredits = request.MaxSmsCredits,
            MaxDeliveryOrders = request.MaxDeliveryOrders,
            FeaturePoliciesJson = request.FeaturePoliciesJson,
            IsActive = request.IsActive,
            SortOrder = request.SortOrder
        };

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

        return package.ToDto();
    }
}
