from datetime import datetime
from sqlalchemy import Column, DateTime, Integer, String, Text
from db import Base, CRUD
import utils


class Category(Base):
    __tablename__ = "categories"

    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, unique=True, index=True)
    description = Column(Text, nullable=True)
    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 utils.toDict(self)

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

    async def edit(id: int, **kwargs):
        return await CRUD.update(Category, id, **kwargs)
