"""User model."""
from datetime import datetime
from typing import Optional, List
from sqlalchemy import String, Boolean, DateTime, Integer
from sqlalchemy.orm import Mapped, mapped_column, relationship

from app.database import Base


class User(Base):
    """User model for authentication and domain tracking."""
    
    __tablename__ = "users"
    
    id: Mapped[int] = mapped_column(primary_key=True, index=True)
    email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
    hashed_password: Mapped[str] = mapped_column(String(255), nullable=False)
    
    # Profile
    name: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    
    # Stripe
    stripe_customer_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    
    # Status
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    is_verified: Mapped[bool] = mapped_column(Boolean, default=False)
    is_admin: Mapped[bool] = mapped_column(Boolean, default=False)
    
    # Password Reset
    password_reset_token: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    password_reset_expires: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    
    # Email Verification
    email_verification_token: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    email_verification_expires: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    
    # OAuth
    oauth_provider: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)  # 'google', 'github'
    oauth_id: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    oauth_avatar: Mapped[Optional[str]] = mapped_column(String(500), nullable=True)
    
    # Yield Referral Tracking (for viral growth)
    referred_by_user_id: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)  # User who referred this user
    referred_by_domain: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)  # Domain that referred
    referral_code: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)  # Original referral code
    invite_code: Mapped[Optional[str]] = mapped_column(String(32), nullable=True, unique=True, index=True)  # user's own code
    
    # Timestamps
    created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, default=datetime.utcnow, onupdate=datetime.utcnow
    )
    last_login: Mapped[Optional[datetime]] = mapped_column(DateTime, nullable=True)
    
    # Relationships
    domains: Mapped[List["Domain"]] = relationship(
        "Domain", back_populates="user", cascade="all, delete-orphan"
    )
    subscription: Mapped["Subscription"] = relationship(
        "Subscription", back_populates="user", uselist=False, cascade="all, delete-orphan"
    )
    portfolio_domains: Mapped[List["PortfolioDomain"]] = relationship(
        "PortfolioDomain", back_populates="user", cascade="all, delete-orphan"
    )
    price_alerts: Mapped[List["PriceAlert"]] = relationship(
        "PriceAlert", cascade="all, delete-orphan", passive_deletes=True
    )
    # For Sale Marketplace
    listings: Mapped[List["DomainListing"]] = relationship(
        "DomainListing", back_populates="user", cascade="all, delete-orphan"
    )
    # Sniper Alerts
    sniper_alerts: Mapped[List["SniperAlert"]] = relationship(
        "SniperAlert", back_populates="user", cascade="all, delete-orphan"
    )
    # Yield Domains
    yield_domains: Mapped[List["YieldDomain"]] = relationship(
        "YieldDomain", back_populates="user", cascade="all, delete-orphan"
    )
    yield_payouts: Mapped[List["YieldPayout"]] = relationship(
        "YieldPayout", back_populates="user", cascade="all, delete-orphan"
    )
    
    def __repr__(self) -> str:
        return f"<User {self.email}>"

    # Property aliases for compatibility
    @property
    def password_hash(self) -> str:
        return self.hashed_password
    
    @password_hash.setter
    def password_hash(self, value: str):
        self.hashed_password = value
