import json

from sqlalchemy import (
    Column,
    BigInteger,
    Integer,
    String,
    Boolean,
    DateTime,
    JSON,
    func,
)
from sqlalchemy.dialects.postgresql import JSONB

from app import db
from core.domains.notification.entity.notification_entity import NotificationEntity
from core.domains.notification.enum.notification_enum import NotificationStatusEnum


class NotificationModel(db.Model):
    __tablename__ = "notifications"

    id = Column(
        BigInteger().with_variant(Integer, "sqlite"), primary_key=True, nullable=False
    )
    user_id = Column(BigInteger, nullable=False, index=True)
    token = Column(String(170), nullable=False)
    endpoint = Column(String(100), nullable=True, default="")
    uuid = Column(String(36), nullable=True)
    topic = Column(String(10), nullable=False, index=True)
    status = Column(
        String(5),
        nullable=False,
        default=NotificationStatusEnum.WAIT.value,
        index=True,
    )
    message = Column(
        "message", JSONB().with_variant(JSON, "sqlite"), nullable=False, default={}
    )
    is_read = Column(Boolean, nullable=False, default=False)
    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_notification_entity(self) -> NotificationEntity:
        title, body = None, None
        if self.message:
            message = json.loads(self.message)
            title = message.get("title")
            body = message.get("body")

        return NotificationEntity(
            id=self.id,
            title=title,
            body=body,
            is_read=self.is_read,
            create_diff_day=None,
            created_at=self.created_at,
        )
