from datetime import datetime
from sqlalchemy import Column, DateTime, ForeignKey, Integer, String, select
from db import CRUD, Base
from utils import answer, logger, toDict


class Document(Base):
    __tablename__ = "documents"

    id = Column(Integer, primary_key=True, index=True)
    singingId = Column(Integer, ForeignKey("signings.id", ondelete="CASCADE"))
    idPatientMis = Column(
        String, ForeignKey("patients.idPatientMis", ondelete="CASCADE")
    )
    number = Column(Integer)
    title = Column(String)
    storagePath = Column(String)
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)

    def __init__(self, **kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

    def toDict(self):
        return toDict(self)

    async def save(self) -> "Document":
        return await CRUD.create(self, refresh=True)

    @staticmethod
    async def addDocument(**kwargs):
        return await Document(**kwargs).save()

    @staticmethod
    async def getDocumentsByIdPatientMisAndNumber(
        idPatientMis: str, number: int, isCheck: bool = False
    ):
        document = await CRUD.read(
            select(Document)
            .where(Document.idPatientMis == idPatientMis)
            .where(Document.number == number),
            True,
        )
        if document:
            return answer(data=document)
        if not isCheck:
            logger.warning(
                f"Документ не найден, idPatientMis: {idPatientMis}, number: {number}"
            )
        return answer(success=False, message="Документ не найден")
