from datetime import datetime
from sqlalchemy import (
    Boolean,
    Column,
    DateTime,
    Float,
    ForeignKey,
    Integer,
    String,
    Text,
)
from sqlalchemy.dialects.postgresql import JSONB
from db import Base, CRUD
import utils


class StocksRecords(Base):
    __tablename__ = "stocks_records"

    id = Column(Integer, primary_key=True, index=True)
    source_stock_id = Column(
        Integer, ForeignKey("stocks.id", ondelete="CASCADE"), nullable=True
    )
    target_stock_id = Column(
        Integer, ForeignKey("stocks.id", ondelete="CASCADE"), nullable=True
    )
    action = Column(String, nullable=False)
    source_toolbox_id = Column(
        Integer, ForeignKey("toolboxes.id", ondelete="CASCADE"), nullable=True
    )
    target_toolbox_id = Column(
        Integer, ForeignKey("toolboxes.id", ondelete="CASCADE"), nullable=True
    )
    toolkit_id = Column(
        Integer, ForeignKey("toolkits.id", ondelete="CASCADE"), nullable=False
    )
    init_user_id = Column(
        Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
    )
    decision_user_id = Column(
        Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True
    )
    reason = Column(Text, nullable=False)
    quantity = Column(Integer, nullable=False)
    price = Column(Float, nullable=False)
    accepted = Column(Boolean, default=None, nullable=True)
    edit_user_id = Column(
        Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True
    )
    edited = Column(JSONB, nullable=True)
    created_at = Column(DateTime, default=datetime.now)
    decided_at = Column(DateTime, nullable=True)
    edited_at = Column(DateTime, nullable=True)
    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(self, **kwargs):
        return await CRUD.update(StocksRecords, self.id, **kwargs)


class ServicesRecords(Base):
    __tablename__ = "services_records"

    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=True)
    details = Column(JSONB, nullable=False)
    created_at = Column(DateTime, default=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)
