from sqlalchemy import (
    Column,
    BigInteger,
    Integer,
    String,
    ForeignKey,
    DateTime,
    func,
)

from app import db
from app.persistence.model import UserModel
from core.domains.user.entity.user_entity import NotificationTokenEntity


class NotificationTokenModel(db.Model):
    __tablename__ = "notification_tokens"

    id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        primary_key=True,
        nullable=False,
        autoincrement=True,
    )
    user_id = Column(
        BigInteger, ForeignKey(UserModel.id), nullable=False, unique=True, index=True
    )
    token = Column(String(170), nullable=True)
    endpoint = Column(String(100), nullable=True)
    created_at = Column(DateTime(), server_default=func.now(), nullable=False)
    updated_at = Column(
        DateTime(), server_default=func.now(), onupdate=func.now(), nullable=False
    )

    def to_entity(self) -> NotificationTokenEntity:
        return NotificationTokenEntity(
            id=self.id, user_id=self.user_id, token=self.token, endpoint=self.endpoint,
        )
