# app/models/user.py
from sqlalchemy import Column, String, DateTime, Integer, Boolean, func, Index, Computed
from sqlalchemy.dialects.mysql import BIGINT
from sqlalchemy.orm import relationship
from app.db.base import Base
from app.core.time import now

class User(Base):
    __tablename__ = "users"

    id = Column(BIGINT(unsigned=True), primary_key=True, autoincrement=True)
    is_admin = Column(Boolean, default=False, nullable=False)
    email = Column(String(255), nullable=False, index=True)
    password = Column(String(255), nullable=False)
    first_name = Column(String(50), nullable=False)
    last_name = Column(String(50), nullable=False)
    phone_code = Column(String(5), nullable=False)
    phone = Column(String(15), nullable=False)
    gender = Column(String(1), nullable=False, comment="M for Male, F for Female")
    birth_date = Column("birthday", String(10), nullable=False, comment="YYYY-MM-DD")
    daily_step_goal = Column(Integer, nullable=False, default=10000)
    profile_image = Column(String(255), nullable=True, default="profile/default_avatar.png")
    background_image = Column(String(255), nullable=True)
    reference_code = Column(String(6), nullable=False, unique=True)
    reference_code_used = Column(String(6), nullable=True)
    health_sync_status = Column(Boolean, default=False)
    last_login = Column(DateTime, nullable=True)
    status = Column(Integer, nullable=False, default=1)
    country_code = Column(String(2), nullable=False, default="TR")
    # New fields for step notification
    step_notification_frequency = Column(Integer, default=3, nullable=False)  # 하루 최대 알림 횟수
    last_step_notification_time = Column(DateTime, nullable=True)  # 마지막 알림 보낸 시간
    step_notifications_sent_today = Column(Integer, default=0, nullable=False)  # 오늘 보낸 알림 수
    created_at = Column(DateTime, nullable=False, default=now)
    updated_at = Column(
        DateTime,
        nullable=False,
        default=now,
        onupdate=now
    )

    # Generated computed column: active_email will contain email only if the user is active (status = 1), else NULL.
    active_email = Column(
        String(255),
        Computed("IF(status = 1, email, NULL)", persisted=False),
        nullable=True
    )

    # 주소와의 관계 정의
    addresses = relationship("UserAddress", back_populates="user", cascade="all, delete-orphan")

    # Create a unique index on the computed column. MySQL allows multiple NULL values.
    __table_args__ = (
        Index("ix_users_active_email", active_email, unique=True),
        Index("idx_country", "country_code"),
    )