"""
Approval requests track the lifecycle of tool execution approvals.

Created when a tool is blocked in enforcement mode, resolved when
an authorized approver approves or rejects the request.
"""

from sqlalchemy import Column, String, DateTime, JSON, Text, Index, ForeignKey, text, desc
from sqlalchemy.dialects.postgresql import UUID
from datetime import datetime

from control_plane_api.app.database import Base


class ApprovalRequest(Base):
    """Tracks approval request lifecycle for blocked tool executions."""

    __tablename__ = "approval_requests"

    id = Column(UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()"))
    organization_id = Column(String(255), nullable=False)

    # Links to execution and rule
    execution_id = Column(String(255), nullable=False)
    rule_id = Column(UUID(as_uuid=True), nullable=True)

    # Status
    status = Column(String(50), nullable=False, default="pending", server_default=text("'pending'"))

    # Requester info
    requester_email = Column(String(255), nullable=True)
    requester_id = Column(String(255), nullable=True)

    # Tool details
    tool_name = Column(String(255), nullable=False)
    tool_args = Column(JSON, nullable=True)
    risk_level = Column(String(50), nullable=True)
    enforcement_context = Column(JSON, nullable=True)

    # Approver info
    approver_emails = Column(JSON, nullable=True)  # who can approve
    approved_by_email = Column(String(255), nullable=True)
    approved_by_name = Column(String(255), nullable=True)
    rejection_reason = Column(Text, nullable=True)

    # Timestamps
    resolved_at = Column(DateTime(timezone=False), nullable=True)
    expires_at = Column(DateTime(timezone=False), nullable=True)
    created_at = Column(DateTime(timezone=False), nullable=True, default=datetime.utcnow, server_default=text("now()"))
    updated_at = Column(DateTime(timezone=False), nullable=True, default=datetime.utcnow, server_default=text("now()"), onupdate=datetime.utcnow)

    __table_args__ = (
        Index('idx_approval_requests_org', 'organization_id'),
        Index('idx_approval_requests_execution', 'execution_id'),
        Index('idx_approval_requests_status', 'status'),
        Index('idx_approval_requests_requester', 'requester_email'),
        Index('idx_approval_requests_created', desc('created_at')),
        {'schema': 'public'}
    )

    def __repr__(self):
        return f"<ApprovalRequest {self.id} tool={self.tool_name} status={self.status}>"
