using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Targeting;

/// <summary>
/// 目标受众上下文构建器。
/// </summary>
internal static class AnnouncementTargetContextFactory
{
    /// <summary>
    /// 构建当前用户的目标上下文。
    /// </summary>
    public static async Task<AnnouncementTargetContext> BuildAsync(
        ITenantProvider tenantProvider,
        ICurrentUserAccessor? currentUserAccessor,
        IAdminAuthService? adminAuthService,
        IMiniAuthService? miniAuthService,
        CancellationToken cancellationToken)
    {
        var tenantId = tenantProvider.GetCurrentTenantId();
        var userId = currentUserAccessor?.UserId ?? 0;
        long? merchantId = null;
        IReadOnlyCollection<string> roles = Array.Empty<string>();
        IReadOnlyCollection<string> permissions = Array.Empty<string>();

        if (userId != 0)
        {
            CurrentUserProfile? profile = null;
            if (adminAuthService != null)
            {
                profile = await adminAuthService.GetProfileAsync(userId, cancellationToken);
            }
            else if (miniAuthService != null)
            {
                profile = await miniAuthService.GetProfileAsync(userId, cancellationToken);
            }

            if (profile != null)
            {
                merchantId = profile.MerchantId;
                roles = profile.Roles ?? Array.Empty<string>();
                permissions = profile.Permissions ?? Array.Empty<string>();
            }
        }

        return new AnnouncementTargetContext
        {
            TenantId = tenantId,
            UserId = userId,
            MerchantId = merchantId,
            Roles = roles,
            Permissions = permissions
        };
    }
}
