from datetime import datetime
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean, ForeignKey, JSON
from sqlalchemy.orm import relationship
from app.core.database import Base


class AlertRule(Base):
    __tablename__ = "alert_rule"

    id = Column(Integer, primary_key=True, index=True)
    name = Column(String(200), nullable=False)
    trigger_condition = Column(String(50), nullable=False)  # l5_count, risk_score, schema_change
    threshold = Column(Integer, default=0)
    severity = Column(String(20), default="medium")
    is_active = Column(Boolean, default=True)
    created_at = Column(DateTime, default=datetime.utcnow)


class AlertRecord(Base):
    __tablename__ = "alert_record"

    id = Column(Integer, primary_key=True, index=True)
    rule_id = Column(Integer, ForeignKey("alert_rule.id"), nullable=False)
    title = Column(String(200), nullable=False)
    content = Column(Text)
    severity = Column(String(20), default="medium")
    status = Column(String(20), default="open")  # open, acknowledged, resolved
    created_at = Column(DateTime, default=datetime.utcnow)

    rule = relationship("AlertRule")


class WorkOrder(Base):
    __tablename__ = "work_order"

    id = Column(Integer, primary_key=True, index=True)
    alert_id = Column(Integer, ForeignKey("alert_record.id"), nullable=True)
    title = Column(String(200), nullable=False)
    description = Column(Text)
    assignee_id = Column(Integer, ForeignKey("sys_user.id"), nullable=True)
    status = Column(String(20), default="open")  # open, in_progress, resolved
    resolution = Column(Text)
    created_at = Column(DateTime, default=datetime.utcnow)
    resolved_at = Column(DateTime, nullable=True)

    assignee = relationship("User")
