using FreeSql.DataAnnotations;
using BookmarkApi.Shared.Enums;

namespace BookmarkApi.Data.Entities;

/// <summary>
/// 分享链接实体
/// </summary>
[Table(Name = "bookmark_shares")]
[Index("idx_share_code", nameof(ShareCode), IsUnique = true)]
[Index("idx_share_user", nameof(UserId))]
[Index("idx_share_target", nameof(ShareType) + "," + nameof(TargetId))]
public class BookmarkShare
{
    /// <summary>
    /// 分享ID
    /// </summary>
    [Column(IsPrimary = true)]
    public Guid Id { get; set; }

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

    /// <summary>
    /// 分享码（短链接标识）
    /// </summary>
    [Column(IsNullable = false, StringLength = 50)]
    public string ShareCode { get; set; } = string.Empty;

    /// <summary>
    /// 分享类型
    /// </summary>
    [Column(MapType = typeof(int), IsNullable = false)]
    public ShareType ShareType { get; set; }

    /// <summary>
    /// 目标ID（书签/文件夹/集合的ID）
    /// </summary>
    [Column(IsNullable = false)]
    public Guid TargetId { get; set; }

    /// <summary>
    /// 分享标题（可自定义）
    /// </summary>
    [Column(StringLength = 200)]
    public string? Title { get; set; }

    /// <summary>
    /// 访问密码（加密存储）
    /// </summary>
    [Column(StringLength = 100)]
    public string? Password { get; set; }

    /// <summary>
    /// 查看次数
    /// </summary>
    [Column(IsNullable = false)]
    public int ViewCount { get; set; }

    /// <summary>
    /// 最大查看次数（null 为无限）
    /// </summary>
    public int? MaxViews { get; set; }

    /// <summary>
    /// 过期时间（null 为永不过期）
    /// </summary>
    public DateTime? ExpiresAt { get; set; }

    /// <summary>
    /// 是否启用
    /// </summary>
    [Column(IsNullable = false)]
    public bool IsActive { get; set; } = true;

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

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

    /// <summary>
    /// 检查分享是否有效
    /// </summary>
    public bool IsValid => IsActive
        && (ExpiresAt == null || DateTime.UtcNow < ExpiresAt)
        && (MaxViews == null || ViewCount < MaxViews);
}
