from app.core.database import Base
from sqlalchemy import Column, Integer, String, Boolean, DateTime, Enum, JSON
import enum
from datetime import datetime


class UserRole(enum.Enum):
    user = "user"
    manager = "manager"
    admin = "admin"


class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, nullable=False)
    email = Column(String, nullable=False, unique=True, index=True)
    hashed_password = Column(String, nullable=False)
    # Hinweis: hashed_pin als unique kann problematisch sein, falls None – in deiner DB ist es gesetzt.
    hashed_pin = Column(String, nullable=False, unique=True, index=True)

    # Sichtbarkeit/Alias für die Stats-Seite
    alias = Column(String, nullable=True, unique=True)
    public_stats = Column(Boolean, nullable=False, default=False)  # <— NEU: Opt-in

    paypal_email = Column(String, nullable=True)
    role = Column(Enum(UserRole), nullable=False, default=UserRole.user)
    is_active = Column(Boolean, default=True)

    created_at = Column(DateTime, default=datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)

    balance_cents = Column(Integer, nullable=False, default=0)
    favorites = Column(JSON, nullable=False, default=list)
    avatar_url = Column(String, nullable=True)

    # PIN-Sicherheit (Lockout etc.)
    from sqlalchemy import String as SQLAString
    pin_lookup = Column(SQLAString(64), index=True, nullable=True)      # HMAC-SHA256(PEPPER, pin)
    pin_fail_count = Column(Integer, nullable=False, default=0)
    pin_locked_until = Column(DateTime, nullable=True)
