from datetime import datetime, timedelta

from pytz import timezone
from sqlalchemy import (
    Column,
    BigInteger,
    Integer,
    String,
    DateTime,
    func,
    ForeignKey,
    SmallInteger,
)
from sqlalchemy.orm import relationship, backref

from app import db
from app.extensions.utils.time_helper import get_server_timestamp
from app.persistence.model import UserModel
from app.persistence.model.plant_category_model import PlantCategoryModel
from core.domains.plant.entity.plant_entity import PlantProfileEntity


class PlantProfileModel(db.Model):
    __tablename__ = "plant_profiles"

    id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        primary_key=True,
        nullable=False,
        autoincrement=True,
    )
    user_id = Column(
        BigInteger().with_variant(Integer, "sqlite"),
        ForeignKey(UserModel.id),
        nullable=False,
        unique=True,
        index=True,
    )
    name = Column(String(50), nullable=False)
    start_growing_date = Column(String(8), nullable=False)
    plant_category_id = Column(
        SmallInteger, ForeignKey(PlantCategoryModel.id), nullable=False, 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
    )

    plant_infos = relationship(
        "PlantInfoModel", backref=backref("plant_infos"), uselist=True
    )
    plant_category = relationship(
        "PlantCategoryModel", backref=backref("plant_profiles"), uselist=False
    )

    def to_entity(self) -> PlantProfileEntity:
        start_growing_diff_date = None
        if self.start_growing_date:
            start_growing_diff_date = get_server_timestamp() - datetime.strptime(
                self.start_growing_date, "%Y%m%d"
            ).replace(tzinfo=timezone("Asia/Seoul"))
            start_growing_diff_date = start_growing_diff_date + timedelta(days=1)
            start_growing_diff_date = str(start_growing_diff_date.days)

        return PlantProfileEntity(
            id=self.id,
            user_id=self.user_id,
            name=self.name,
            start_growing_date=self.start_growing_date,
            start_growing_diff_date=start_growing_diff_date,
            plant_category_id=self.plant_category_id,
            plant_infos=[plant_info.to_entity() for plant_info in self.plant_infos]
            if self.plant_infos
            else None,
        )
