using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace HoneyBox.Admin.Entities;

/// <summary>
/// 刷新令牌
/// </summary>
[Table("refresh_tokens")]
public class RefreshToken
{
    /// <summary>
    /// 主键ID
    /// </summary>
    [Key]
    public long Id { get; set; }

    /// <summary>
    /// 管理员用户ID
    /// </summary>
    public long AdminUserId { get; set; }

    /// <summary>
    /// Token哈希值（不存明文）
    /// </summary>
    [Required]
    [MaxLength(256)]
    public string TokenHash { get; set; } = null!;

    /// <summary>
    /// 过期时间
    /// </summary>
    public DateTime ExpiresAt { get; set; }

    /// <summary>
    /// 创建时间
    /// </summary>
    public DateTime CreatedAt { get; set; } = DateTime.Now;

    /// <summary>
    /// 创建时的IP地址
    /// </summary>
    [MaxLength(50)]
    public string? CreatedByIp { get; set; }

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

    /// <summary>
    /// 撤销时的IP地址
    /// </summary>
    [MaxLength(50)]
    public string? RevokedByIp { get; set; }

    /// <summary>
    /// 被替换的新Token哈希（用于Token轮换追踪）
    /// </summary>
    [MaxLength(256)]
    public string? ReplacedByToken { get; set; }

    #region 计算属性

    /// <summary>
    /// 是否已过期
    /// </summary>
    [NotMapped]
    public bool IsExpired => DateTime.Now >= ExpiresAt;

    /// <summary>
    /// 是否已撤销
    /// </summary>
    [NotMapped]
    public bool IsRevoked => RevokedAt != null;

    /// <summary>
    /// 是否有效（未过期且未撤销）
    /// </summary>
    [NotMapped]
    public bool IsActive => !IsRevoked && !IsExpired;

    #endregion

    #region 导航属性

    /// <summary>
    /// 关联的管理员用户
    /// </summary>
    [ForeignKey("AdminUserId")]
    public virtual AdminUser AdminUser { get; set; } = null!;

    #endregion
}
