using MediatR;
using TakeoutSaaS.Application.App.Tenants.Commands;
using TakeoutSaaS.Application.Identity.Abstractions;
using TakeoutSaaS.Application.Identity.Contracts;
using TakeoutSaaS.Domain.Identity.Repositories;
using TakeoutSaaS.Domain.Tenants.Entities;
using TakeoutSaaS.Domain.Tenants.Enums;
using TakeoutSaaS.Domain.Tenants.Repositories;
using TakeoutSaaS.Shared.Abstractions.Constants;
using TakeoutSaaS.Shared.Abstractions.Exceptions;
using TakeoutSaaS.Shared.Abstractions.Security;
using TakeoutSaaS.Shared.Abstractions.Tenancy;

namespace TakeoutSaaS.Application.App.Tenants.Handlers;

/// <summary>
/// 伪装登录租户处理器（平台超级管理员使用）。
/// </summary>
public sealed class ImpersonateTenantCommandHandler(
    ITenantRepository tenantRepository,
    ITenantProvider tenantProvider,
    ITenantContextAccessor tenantContextAccessor,
    IIdentityUserRepository identityUserRepository,
    ICurrentUserAccessor currentUserAccessor,
    IAdminAuthService adminAuthService,
    IJwtTokenService jwtTokenService)
    : IRequestHandler<ImpersonateTenantCommand, TokenResponse>
{
    private const long PlatformRootTenantId = 1000000000001;

    /// <inheritdoc />
    public async Task<TokenResponse> Handle(ImpersonateTenantCommand request, CancellationToken cancellationToken)
    {
        // 1. 校验仅允许平台超级管理员执行
        var currentTenantId = tenantProvider.GetCurrentTenantId();
        if (currentTenantId != PlatformRootTenantId)
        {
            throw new BusinessException(ErrorCodes.Forbidden, "仅平台超级管理员可执行伪装登录");
        }

        // 2. (空行后) 读取操作者信息（在平台租户上下文内）
        var operatorProfile = await adminAuthService.GetProfileAsync(currentUserAccessor.UserId, cancellationToken);
        var operatorName = string.IsNullOrWhiteSpace(operatorProfile.DisplayName)
            ? $"user:{currentUserAccessor.UserId}"
            : operatorProfile.DisplayName;

        // 2. (空行后) 校验租户存在且存在主管理员
        var tenant = await tenantRepository.FindByIdAsync(request.TenantId, cancellationToken)
            ?? throw new BusinessException(ErrorCodes.NotFound, "租户不存在");

        // 2.1 (空行后) 若缺少主管理员则自动回填（兼容历史数据）
        if (!tenant.PrimaryOwnerUserId.HasValue || tenant.PrimaryOwnerUserId.Value == 0)
        {
            var originalContextForFix = tenantContextAccessor.Current;
            tenantContextAccessor.Current = new TenantContext(tenant.Id, tenant.Code, "admin:impersonate:fix-owner");
            try
            {
                var users = await identityUserRepository.SearchAsync(tenant.Id, keyword: null, cancellationToken);
                var ownerCandidate = users.OrderBy(x => x.CreatedAt).FirstOrDefault();
                if (ownerCandidate == null)
                {
                    throw new BusinessException(ErrorCodes.BadRequest, "该租户未配置主管理员账号，且未找到可用管理员账号");
                }

                tenant.PrimaryOwnerUserId = ownerCandidate.Id;
                await tenantRepository.UpdateTenantAsync(tenant, cancellationToken);
                await tenantRepository.SaveChangesAsync(cancellationToken);
            }
            finally
            {
                tenantContextAccessor.Current = originalContextForFix;
            }
        }

        // 3. (空行后) 进入目标租户上下文以读取租户内用户（避免多租户查询过滤导致找不到用户）
        var originalTenantContext = tenantContextAccessor.Current;
        tenantContextAccessor.Current = new TenantContext(tenant.Id, null, "admin:impersonate");
        try
        {
            // 4. 为租户主管理员签发令牌
            var targetProfile = await adminAuthService.GetProfileAsync(tenant.PrimaryOwnerUserId.Value, cancellationToken);
            var token = await jwtTokenService.CreateTokensAsync(targetProfile, false, cancellationToken);

            // 5. (空行后) 恢复租户上下文后写入审计日志
            tenantContextAccessor.Current = originalTenantContext;
            var auditLog = new TenantAuditLog
            {
                TenantId = tenant.Id,
                Action = TenantAuditAction.ImpersonatedLogin,
                Title = "伪装登录",
                Description = $"操作者：{operatorName}，目标账号：{targetProfile.Account}",
                OperatorId = currentUserAccessor.UserId,
                OperatorName = operatorName,
                PreviousStatus = tenant.Status,
                CurrentStatus = tenant.Status
            };
            await tenantRepository.AddAuditLogAsync(auditLog, cancellationToken);
            await tenantRepository.SaveChangesAsync(cancellationToken);

            // 6. (空行后) 返回令牌
            return token;
        }
        finally
        {
            // 7. (空行后) 确保恢复租户上下文
            tenantContextAccessor.Current = originalTenantContext;
        }
    }
}
