from sqlalchemy import Column, Integer, String, DateTime, Float, Enum, ForeignKey, UniqueConstraint
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from app.models import Base
from app.config import TABLE_PREFIX
import enum

class TargetType(str, enum.Enum):
    SAMPLE = "SAMPLE"
    ORDER = "ORDER"

class MatchStatus(str, enum.Enum):
    pending = "pending"
    accepted = "accepted"
    rejected = "rejected"
    auto_matched = "auto_matched"

class ReviewAction(str, enum.Enum):
    accept = "accept"
    reject = "reject"

class MatchResult(Base):
    __tablename__ = f"{TABLE_PREFIX}Match_Results"
    __table_args__ = (
        UniqueConstraint('dit_id', 'target_type', 'target_id', name='uix_match_dit_target'),
    )

    id = Column(Integer, primary_key=True, index=True)
    dit_id = Column(Integer, ForeignKey(f"{TABLE_PREFIX}DIT_Records.id"), nullable=False)
    target_type = Column(Enum(TargetType), nullable=False)
    target_id = Column(Integer, nullable=False)
    score = Column(Float, nullable=False)
    match_priority = Column(Integer, default=3) # 1: Oppy ID, 2: Account, 3: Name
    match_source = Column(String(255)) # e.g., "Matched via Opportunity ID: OP12345"
    reason = Column(String(255))
    status = Column(Enum(MatchStatus), default=MatchStatus.pending)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())

    dit = relationship("DitRecord", backref="matches")

class ReviewLog(Base):
    __tablename__ = f"{TABLE_PREFIX}Review_Logs"

    id = Column(Integer, primary_key=True, index=True)
    match_id = Column(Integer, ForeignKey(f"{TABLE_PREFIX}Match_Results.id"), nullable=False)
    user_id = Column(Integer, ForeignKey(f"{TABLE_PREFIX}users.id"), nullable=False)
    action = Column(Enum(ReviewAction), nullable=False)
    timestamp = Column(DateTime(timezone=True), server_default=func.now())

    match_result = relationship("MatchResult", backref="review_logs")
    user = relationship("User", backref="review_logs")
