using Volo.Abp.Domain.Services;
using Volo.Abp.Users;
using Yi.Framework.AiHub.Domain.Entities.OpenApi;
using Yi.Framework.SqlSugarCore.Abstractions;

namespace Yi.Framework.AiHub.Domain.Managers;

public class TokenManager : DomainService
{
    private readonly ISqlSugarRepository<TokenAggregateRoot> _tokenRepository;

    public TokenManager(ISqlSugarRepository<TokenAggregateRoot> tokenRepository)
    {
        _tokenRepository = tokenRepository;
    }

    public async Task<string?> GetAsync(Guid userId)
    {
        var entity = await _tokenRepository._DbQueryable.FirstAsync(x => x.UserId == userId);
        if (entity is not null)
        {
            return entity.Token;
        }
        else
        {
            return null;
        }
    }

    public async Task CreateAsync(Guid userId)
    {
        var entity = await _tokenRepository._DbQueryable.FirstAsync(x => x.UserId == userId);
        if (entity is not null)
        {
            entity.ResetToken();
            await _tokenRepository.UpdateAsync(entity);
        }
        else
        {
            var token = new TokenAggregateRoot(userId);
            await _tokenRepository.InsertAsync(token);
        }
    }

    public async Task<Guid> GetUserIdAsync(string? token)
    {
        if (token is null)
        {
            throw new UserFriendlyException("当前请求未包含token", "401");
        }

        if (token.StartsWith("yi-"))
        {
            var entity = await _tokenRepository._DbQueryable.Where(x => x.Token == token).FirstAsync();
            if (entity is null)
            {
                throw new UserFriendlyException("当前请求token无效", "401");
            }

            return entity.UserId;
        }
        throw new UserFriendlyException("当前请求token非法", "401");
    }
}