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

namespace HoneyBox.Model.Entities;

/// <summary>
/// 用户刷新令牌表，存储 Refresh Token 信息用于双 Token 认证机制
/// </summary>
public class UserRefreshToken
{
    /// <summary>
    /// 主键ID
    /// </summary>
    public long Id { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public int UserId { get; set; }

    /// <summary>
    /// Token 哈希值（SHA256）
    /// </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; }

    /// <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;

    /// <summary>
    /// 关联的用户
    /// </summary>
    [ForeignKey("UserId")]
    public virtual User User { get; set; } = null!;
}
