from sqlalchemy import create_engine, Column, Integer, String, DateTime, ForeignKey, Boolean
from sqlalchemy.orm import declarative_base, relationship, sessionmaker
from datetime import datetime

Base = declarative_base()

class ProposalJob(Base):
    __tablename__ = 'proposal_jobs'

    id = Column(Integer, primary_key=True)
    job_uuid = Column(String, unique=True, nullable=False)  # Für die API-Links
    customer_email = Column(String, nullable=False)
    customer_name = Column(String, nullable=True)
    customer_company = Column(String, nullable=True)
    
    # Status-Tracking
    status = Column(String, default='pending')  # pending, approved, rejected, sent, failed
    
    # Audit-Trail
    created_at = Column(DateTime, default=datetime.now)
    updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
    approved_at = Column(DateTime, nullable=True)
    
    # Verknüpfung zu den vorgeschlagenen Slots
    slots = relationship("ProposedSlot", back_populates="job")

class ProposedSlot(Base):
    __tablename__ = 'proposed_slots'

    id = Column(Integer, primary_key=True)
    job_id = Column(Integer, ForeignKey('proposal_jobs.id'))
    
    start_time = Column(DateTime, nullable=False)
    end_time = Column(DateTime, nullable=False)
    
    # Wir brauchen kein 'is_blocked' Flag mehr, da wir dynamisch zählen,
    # wie oft 'start_time' in den letzten 24h verwendet wurde.
    
    job = relationship("ProposalJob", back_populates="slots")

# DB Setup Helper
def init_db(db_path='sqlite:///trading_twins/trading_twins.db'):
    engine = create_engine(db_path)
    Base.metadata.create_all(engine)
    return sessionmaker(bind=engine)
