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

from app import db
from core.domains.cs.entity.cs_entity import CustomerInquiryEntity


class CustomerInquiryModel(db.Model):
    __tablename__ = "customer_inquiries"

    id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        primary_key=True,
        nullable=False,
        autoincrement=True,
    )
    user_id = Column(BigInteger().with_variant(Integer, "sqlite"), index=True)
    email = Column(String(75), nullable=False)
    title = Column(String(100), nullable=False)
    body = Column(Text, nullable=False)
    is_solved = 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
    )

    inquiry_attachments = relationship(
        "InquiryAttachmentModel", backref=backref("customer_inquiries"), uselist=True
    )

    def to_entity(self) -> CustomerInquiryEntity:
        created_date = self.created_at.strftime("%y.%m.%d")
        return CustomerInquiryEntity(
            id=self.id,
            user_id=self.user_id,
            email=self.email,
            title=self.title,
            body=self.body,
            is_solved=self.is_solved,
            created_date=created_date,
            created_at=self.created_at,
            inquiry_attachments=[
                inquiry_attachment.to_entity()
                for inquiry_attachment in self.inquiry_attachments
            ]
            if self.inquiry_attachments
            else None,
        )
