using ColaFlow.Shared.Kernel.Common;
using ColaFlow.Modules.Identity.Domain.Aggregates.Users;

namespace ColaFlow.Modules.Identity.Domain.Entities;

/// <summary>
/// Email verification token entity.
/// Lifetime: 24 hours.
/// </summary>
public sealed class EmailVerificationToken : Entity
{
    public UserId UserId { get; private set; } = null!;
    public string TokenHash { get; private set; } = string.Empty;
    public DateTime ExpiresAt { get; private set; }
    public DateTime? VerifiedAt { get; private set; }
    public DateTime CreatedAt { get; private set; }

    // Private constructor for EF Core
    private EmailVerificationToken() : base()
    {
    }

    /// <summary>
    /// Factory method to create new verification token.
    /// </summary>
    public static EmailVerificationToken Create(
        UserId userId,
        string tokenHash,
        DateTime expiresAt)
    {
        return new EmailVerificationToken
        {
            Id = Guid.NewGuid(),
            UserId = userId,
            TokenHash = tokenHash,
            ExpiresAt = expiresAt,
            CreatedAt = DateTime.UtcNow
        };
    }

    public bool IsExpired => DateTime.UtcNow > ExpiresAt;
    public bool IsVerified => VerifiedAt.HasValue;
    public bool IsValid => !IsExpired && !IsVerified;

    public void MarkAsVerified()
    {
        if (!IsValid)
            throw new InvalidOperationException("Token is not valid for verification");

        VerifiedAt = DateTime.UtcNow;
    }
}
