from sqlalchemy import Column, Integer, String, Numeric, Text, Enum, ForeignKey, DateTime, JSON
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base

class TransactionType(str, enum.Enum):
    consumption = 'consumption'  # Used in tasks
    adjustment = 'adjustment'  # Manual adjustment (correction)
    received = 'received'  # Stock received from supplier
    transfer = 'transfer'  # Transfer between locations
    damaged = 'damaged'  # Damaged/lost items
    returned = 'returned'  # Returned to supplier

class InventoryTransaction(Base):
    __tablename__ = 'inventory_transactions'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    item_id = Column(Integer, ForeignKey('inventory_items.id'), nullable=False, index=True)
    
    transaction_type = Column(Enum(TransactionType), nullable=False)
    quantity = Column(Numeric(10, 2), nullable=False)  # Positive for received, negative for consumption
    quantity_before = Column(Numeric(10, 2), nullable=False)  # Stock before transaction
    quantity_after = Column(Numeric(10, 2), nullable=False)  # Stock after transaction
    
    # Reference
    reference_type = Column(String(50), nullable=True)  # e.g., 'housekeeping_task', 'purchase_order'
    reference_id = Column(Integer, nullable=True, index=True)  # ID of related record
    
    # Details
    notes = Column(Text, nullable=True)
    cost = Column(Numeric(10, 2), nullable=True)  # Cost for this transaction
    
    # User tracking
    performed_by = Column(Integer, ForeignKey('users.id'), nullable=True)
    
    # Timestamp
    transaction_date = Column(DateTime, nullable=False, default=datetime.utcnow, index=True)
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # Relationships
    item = relationship('InventoryItem', back_populates='transactions')

