using MediatR;
using TakeoutSaaS.Application.App.Tenants.Contracts;
using TakeoutSaaS.Application.App.Tenants.Queries;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 获取租户详情查询处理器。
/// </summary>
public sealed class GetTenantDetailQueryHandler(ITenantRepository tenantRepository)
    : IRequestHandler<GetTenantDetailQuery, TenantDetailDto?>
{
    /// <inheritdoc />
    public async Task<TenantDetailDto?> Handle(GetTenantDetailQuery request, CancellationToken cancellationToken)
    {
        // 1. 查询租户详情
        var result = await tenantRepository.GetDetailAsync(request.TenantId, cancellationToken);
        if (result is null)
        {
            return null;
        }

        var (tenant, verification, subscription, package) = result;

        // 2. 映射租户 DTO
        var tenantDto = new Contracts.TenantDto
        {
            Id = tenant.Id,
            Code = tenant.Code,
            Name = tenant.Name,
            ShortName = tenant.ShortName,
            Industry = tenant.Industry,
            ContactName = tenant.ContactName,
            ContactPhone = tenant.ContactPhone,
            ContactEmail = tenant.ContactEmail,
            Status = tenant.Status,
            VerificationStatus = verification?.Status ?? TenantVerificationStatus.Draft,
            OperatingMode = tenant.OperatingMode,
            CurrentPackageId = subscription?.TenantPackageId,
            EffectiveFrom = tenant.EffectiveFrom,
            EffectiveTo = tenant.EffectiveTo,
            AutoRenew = subscription?.AutoRenew ?? false
        };

        // 3. 映射认证 DTO
        Contracts.TenantVerificationDto? verificationDto = null;
        if (verification is not null)
        {
            verificationDto = new Contracts.TenantVerificationDto
            {
                Id = verification.Id,
                TenantId = verification.TenantId,
                Status = verification.Status,
                BusinessLicenseNumber = verification.BusinessLicenseNumber,
                BusinessLicenseUrl = verification.BusinessLicenseUrl,
                LegalPersonName = verification.LegalPersonName,
                LegalPersonIdNumber = verification.LegalPersonIdNumber,
                LegalPersonIdFrontUrl = verification.LegalPersonIdFrontUrl,
                LegalPersonIdBackUrl = verification.LegalPersonIdBackUrl,
                BankAccountName = verification.BankAccountName,
                BankAccountNumber = verification.BankAccountNumber,
                BankName = verification.BankName,
                AdditionalDataJson = verification.AdditionalDataJson,
                SubmittedAt = verification.SubmittedAt,
                ReviewedBy = verification.ReviewedBy,
                ReviewRemarks = verification.ReviewRemarks,
                ReviewedByName = verification.ReviewedByName,
                ReviewedAt = verification.ReviewedAt
            };
        }

        // 4. 映射订阅 DTO
        Contracts.TenantSubscriptionDto? subscriptionDto = null;
        if (subscription is not null)
        {
            subscriptionDto = new Contracts.TenantSubscriptionDto
            {
                Id = subscription.Id,
                TenantId = subscription.TenantId,
                TenantPackageId = subscription.TenantPackageId,
                Status = subscription.Status,
                EffectiveFrom = subscription.EffectiveFrom,
                EffectiveTo = subscription.EffectiveTo,
                NextBillingDate = subscription.NextBillingDate,
                AutoRenew = subscription.AutoRenew
            };
        }

        // 5. 映射套餐 DTO
        Contracts.TenantPackageDto? packageDto = null;
        if (package is not null)
        {
            packageDto = new Contracts.TenantPackageDto
            {
                Id = package.Id,
                Name = package.Name,
                Description = package.Description,
                PackageType = package.PackageType,
                MonthlyPrice = package.MonthlyPrice,
                YearlyPrice = package.YearlyPrice,
                MaxStoreCount = package.MaxStoreCount,
                MaxAccountCount = package.MaxAccountCount,
                MaxStorageGb = package.MaxStorageGb,
                MaxSmsCredits = package.MaxSmsCredits,
                MaxDeliveryOrders = package.MaxDeliveryOrders,
                FeaturePoliciesJson = package.FeaturePoliciesJson,
                IsActive = package.IsActive,
                IsPublicVisible = package.IsPublicVisible,
                IsAllowNewTenantPurchase = package.IsAllowNewTenantPurchase,
                PublishStatus = package.PublishStatus,
                IsRecommended = package.IsRecommended,
                Tags = package.Tags,
                SortOrder = package.SortOrder
            };
        }

        // 6. 组装返回结果
        return new TenantDetailDto
        {
            Tenant = tenantDto,
            Verification = verificationDto,
            Subscription = subscriptionDto,
            Package = packageDto
        };
    }
}
