from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Enum
from sqlalchemy.orm import relationship, Query
from sqlalchemy.sql import func
from database import Base
import enum


class AssetCategory(str, enum.Enum):
    CHARACTERS = "characters"
    PROPS = "props"
    SETS = "sets"
    VEHICLES = "vehicles"


class AssetStatus(str, enum.Enum):
    NOT_STARTED = "not_started"
    IN_PROGRESS = "in_progress"
    ON_HOLD = "on_hold"
    COMPLETED = "completed"
    APPROVED = "approved"


class Asset(Base):
    __tablename__ = "assets"

    id = Column(Integer, primary_key=True, index=True)
    project_id = Column(Integer, ForeignKey("projects.id"), nullable=False)
    name = Column(String, nullable=False, index=True)
    description = Column(String)
    category = Column(Enum(AssetCategory), nullable=False)
    status = Column(Enum(AssetStatus), nullable=False, default=AssetStatus.NOT_STARTED)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), server_default=func.now(), onupdate=func.now())
    
    # Soft deletion columns
    deleted_at = Column(DateTime(timezone=True), nullable=True)
    deleted_by = Column(Integer, ForeignKey("users.id"), nullable=True)

    # Relationships
    project = relationship("Project", back_populates="assets")
    tasks = relationship("Task", back_populates="asset", cascade="all, delete-orphan")
    deleted_by_user = relationship("User", foreign_keys=[deleted_by])

    @property
    def is_deleted(self) -> bool:
        """Check if the asset is soft deleted."""
        return self.deleted_at is not None

    @classmethod
    def query_active(cls, query: Query) -> Query:
        """Filter query to exclude soft deleted assets."""
        return query.filter(cls.deleted_at.is_(None))

    @classmethod
    def query_deleted(cls, query: Query) -> Query:
        """Filter query to include only soft deleted assets."""
        return query.filter(cls.deleted_at.isnot(None))

    @classmethod
    def query_all_including_deleted(cls, query: Query) -> Query:
        """Return query without soft deletion filtering (for admin use)."""
        return query

    def __repr__(self):
        return f"<Asset(id={self.id}, name='{self.name}', category='{self.category}')>"