from sqlalchemy import (
    Column,
    BigInteger,
    DateTime,
    Integer,
    String,
    func,
    Boolean,
)
from sqlalchemy.orm import relationship, backref

from app import db
from core.domains.user.entity.user_entity import UserEntity


class UserModel(db.Model):
    __tablename__ = "users"

    id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        primary_key=True,
        nullable=False,
        autoincrement=True,
    )
    email = Column(String(75), nullable=True)
    join_date = Column(String(8), nullable=False)
    provider = Column(String(10), nullable=False)
    provider_id = Column(String(256), nullable=False)
    group = Column(String(10), nullable=False)
    nickname = Column(String(10), nullable=False)
    is_out = Column(Boolean, nullable=False)
    is_available = Column(Boolean, nullable=False)
    current_connection_time = Column(
        DateTime(), server_default=func.now(), nullable=False
    )
    uuid = Column(String(36), nullable=False)
    created_at = Column(DateTime(), server_default=func.now(), nullable=False)
    updated_at = Column(
        DateTime(), server_default=func.now(), onupdate=func.now(), nullable=False
    )

    # user relationship
    device = relationship("DeviceModel", backref=backref("users"), uselist=False)
    notification_token = relationship(
        "NotificationTokenModel", backref=backref("users"), uselist=False
    )
    receive_push_type = relationship(
        "ReceivePushTypeModel", backref=backref("users"), uselist=False
    )
    user_profile = relationship(
        "UserProfileModel", backref=backref("users"), uselist=False
    )

    # auth relationship
    jwt = relationship("JwtModel", backref=backref("users"), uselist=False)
    blacklists = relationship("BlacklistModel", backref=backref("users"), uselist=True)

    # plant relationship
    plant_profile = relationship(
        "PlantProfileModel", backref=backref("users"), uselist=False
    )

    def to_entity(self) -> UserEntity:
        return UserEntity(
            id=self.id,
            email=self.email,
            join_date=self.join_date,
            provider=self.provider,
            provider_id=self.provider_id,
            group=self.group,
            nickname=self.nickname,
            is_out=self.is_out,
            is_available=self.is_available,
            current_connection_time=self.current_connection_time,
            uuid=self.uuid,
            device=self.device.to_entity(),
            notification_token=self.notification_token.to_entity(),
            receive_push_type=self.receive_push_type.to_entity(),
            user_profile=self.user_profile.to_entity() if self.user_profile else None,
            jwt=self.jwt.to_entity(),
            blacklists=[blacklist.to_entity() for blacklist in self.blacklists]
            if self.blacklists
            else None,
            plant_profile=self.plant_profile.to_entity(),
        )
