using FreeSql.DataAnnotations;

namespace BookmarkApi.Data.Entities;

/// <summary>
/// 刷新令牌实体
/// </summary>
[Table(Name = "refresh_tokens")]
[Index("idx_refreshtoken_token", nameof(Token), IsUnique = true)]
[Index("idx_refreshtoken_user_device", nameof(UserId) + "," + nameof(DeviceId))]
public class RefreshToken
{
    /// <summary>
    /// 令牌ID
    /// </summary>
    [Column(IsPrimary = true)]
    public Guid Id { get; set; }

    /// <summary>
    /// 所属用户ID
    /// </summary>
    [Column(IsNullable = false)]
    public Guid UserId { get; set; }

    /// <summary>
    /// 关联设备ID
    /// </summary>
    [Column(IsNullable = false)]
    public Guid DeviceId { get; set; }

    /// <summary>
    /// 刷新令牌值
    /// </summary>
    [Column(IsNullable = false, StringLength = 500)]
    public string Token { get; set; } = string.Empty;

    /// <summary>
    /// 过期时间
    /// </summary>
    [Column(IsNullable = false)]
    public DateTime ExpiresAt { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    [Column(ServerTime = DateTimeKind.Utc, CanUpdate = false)]
    public DateTime CreatedAt { get; set; }

    /// <summary>
    /// 是否已撤销
    /// </summary>
    [Column(IsNullable = false)]
    public bool IsRevoked { get; set; }

    /// <summary>
    /// 撤销时间
    /// </summary>
    public DateTime? RevokedAt { get; set; }

    /// <summary>
    /// 被替换的令牌ID（令牌刷新时记录）
    /// </summary>
    public Guid? ReplacedByTokenId { get; set; }

    /// <summary>
    /// 导航属性 - 所属用户
    /// </summary>
    [Navigate(nameof(UserId))]
    public virtual User? User { get; set; }

    /// <summary>
    /// 导航属性 - 关联设备
    /// </summary>
    [Navigate(nameof(DeviceId))]
    public virtual Device? Device { get; set; }

    /// <summary>
    /// 检查令牌是否有效
    /// </summary>
    public bool IsActive => !IsRevoked && DateTime.UtcNow < ExpiresAt;
}

