# models/ai_action_audit_log.py

from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text
from datetime import datetime
from database import Base


class AiActionAuditLog(Base):
    """One row per state-CHANGING action the assistant executes on a user's
    behalf — today only a manager's leave approval (FR-07.4).

    Section 10's Audit Logging NFR, verbatim: "Every AI decision or action —
    auto-approval, auto-rejection, cancellation, escalation — shall be logged
    with timestamp, decision basis, and rule version, tagged with
    source = 'AI Assistant.'" Those four are the four non-nullable columns
    below (created_at, decision_basis, rule_version, source); everything else
    is context that makes a row readable months later.

    Deliberately NOT the same table as erp_api_call_logs: that one records
    that a call happened (method, status, latency), which is a transport
    fact. This records WHY an action was taken and on whose explicit
    confirmation, which is a business fact and has to survive independently
    of how the call went over the wire.

    Rows are written for FAILED attempts too (executed=False, plus erp-api's
    own message). The NFR says every action is logged; a refused approval is
    still an action the assistant took on a manager's instruction, and the
    absence of a row is exactly what an audit cannot distinguish from "the
    logging broke".
    """

    __tablename__ = "ai_action_audit_logs"

    id = Column(Integer, primary_key=True, index=True)

    # What was done, and to what.
    action = Column(String, nullable=False)              # "approve"
    resource_type = Column(String, nullable=False)       # "leave_request"
    resource_id = Column(Integer, nullable=True)         # erp-api's leave request id

    # Who it was done for / by. approver_* comes from erp-api's own
    # approved_by block on success — the authoritative record of who the
    # token actually belonged to, rather than anything this service inferred.
    employee_id = Column(Integer, nullable=True)
    employee_name = Column(String, nullable=True)
    approver_id = Column(Integer, nullable=True)
    approver_name = Column(String, nullable=True)

    # NFR fields.
    decision_basis = Column(Text, nullable=False)
    rule_version = Column(String, nullable=False)
    source = Column(String, nullable=False, default="AI Assistant")

    # Outcome.
    executed = Column(Boolean, nullable=False, default=False)
    erp_status = Column(Integer, nullable=True)
    erp_message = Column(Text, nullable=True)

    company_id = Column(Integer, nullable=True)
    conversation_id = Column(String, nullable=True)

    created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
