"""
Approval workflow models for enterprise financial operations.
"""
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum, JSON
from sqlalchemy.orm import relationship
from datetime import datetime
import enum
from ...shared.config.database import Base

class ApprovalStatus(str, enum.Enum):
    pending = "pending"
    approved = "approved"
    rejected = "rejected"
    cancelled = "cancelled"

class ApprovalType(str, enum.Enum):
    invoice_update = "invoice_update"
    payment_refund = "payment_refund"
    invoice_mark_paid = "invoice_mark_paid"
    financial_adjustment = "financial_adjustment"
    user_role_change = "user_role_change"
    large_transaction = "large_transaction"

class ApprovalRequest(Base):
    __tablename__ = 'approval_requests'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    approval_type = Column(Enum(ApprovalType), nullable=False, index=True)
    status = Column(Enum(ApprovalStatus), default=ApprovalStatus.pending, nullable=False, index=True)
    
    # Who requested
    requested_by = Column(Integer, ForeignKey('users.id'), nullable=False, index=True)
    requested_at = Column(DateTime, default=datetime.utcnow, nullable=False)
    
    # Who approved/rejected
    approved_by = Column(Integer, ForeignKey('users.id'), nullable=True, index=True)
    approved_at = Column(DateTime, nullable=True)
    rejection_reason = Column(Text, nullable=True)
    
    # Resource being approved
    resource_type = Column(String(50), nullable=False, index=True)
    resource_id = Column(Integer, nullable=False, index=True)
    
    # Request details
    request_data = Column(JSON, nullable=True)
    current_data = Column(JSON, nullable=True)  # Snapshot of current state
    
    # Metadata
    priority = Column(String(20), default='normal')  # low, normal, high, urgent
    notes = Column(Text, nullable=True)
    extra_metadata = Column(JSON, nullable=True)  # Renamed from 'metadata' as it's reserved in SQLAlchemy
    
    # Relationships
    requester = relationship('User', foreign_keys=[requested_by])
    approver = relationship('User', foreign_keys=[approved_by])
    
    created_at = Column(DateTime, default=datetime.utcnow, nullable=False, index=True)
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)

