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 DeviceEntity


class DeviceModel(db.Model):
    __tablename__ = "devices"

    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
    )
    mobile_os = Column(String(3), nullable=False)
    hw_mac = Column(String(100), nullable=True, index=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) -> DeviceEntity:
        return DeviceEntity(
            id=self.id,
            user_id=self.user_id,
            mobile_os=self.mobile_os,
            hw_mac=self.hw_mac,
        )
