using System.Text;
using SqlSugar;
using Volo.Abp.Domain.Entities.Auditing;

namespace Yi.Framework.AiHub.Domain.Entities.OpenApi;

[SugarTable("Ai_Token")]
public class TokenAggregateRoot : FullAuditedAggregateRoot<Guid>
{
    public TokenAggregateRoot()
    {
    }

    public TokenAggregateRoot(Guid userId)
    {
        this.UserId = userId;
        this.Token = GenerateToken();
    }

    public string Token { get; set; }
    public Guid UserId { get; set; }

    /// <summary>
    /// 重置token
    /// </summary>
    public void ResetToken()
    {
        this.Token = GenerateToken();
    }

    private string GenerateToken(int length = 36)
    {
        // 定义可能的字符集：大写字母、小写字母和数字
        const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

        // 创建随机数生成器
        Random random = new Random();

        // 使用StringBuilder高效构建字符串
        StringBuilder sb = new StringBuilder(length);

        // 生成指定长度的随机字符串
        for (int i = 0; i < length; i++)
        {
            // 从字符集中随机选择一个字符
            int index = random.Next(chars.Length);
            sb.Append(chars[index]);
        }

        return "yi-" + sb.ToString();
    }
}