# /opt/docker/dev/service_finder/backend/app/models/identity/security.py
import enum
from datetime import datetime
from typing import Optional, TYPE_CHECKING
from sqlalchemy import String, Integer, ForeignKey, DateTime, text, Enum
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.sql import func

# MB 2.0: Központi aszinkron adatbázis motorból származó Base
from app.database import Base

if TYPE_CHECKING:
    from .identity import User

class ActionStatus(str, enum.Enum):
    pending = "pending"
    approved = "approved"
    rejected = "rejected"
    expired = "expired"

class PendingAction(Base):
    """ Sentinel: Kritikus műveletek jóváhagyási lánca. """
    __tablename__ = "pending_actions"
    __table_args__ = {"schema": "system"}

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
    
    # JAVÍTÁS: A User az identity sémában van, nem a data-ban!
    requester_id: Mapped[int] = mapped_column(Integer, ForeignKey("identity.users.id"), nullable=False)
    approver_id: Mapped[Optional[int]] = mapped_column(Integer, ForeignKey("identity.users.id"), nullable=True)
    
    status: Mapped[ActionStatus] = mapped_column(
        Enum(ActionStatus, name="actionstatus", schema="system"), 
        default=ActionStatus.pending
    )
    
    action_type: Mapped[str] = mapped_column(String(50)) # pl. "WALLET_ADJUST"
    payload: Mapped[dict] = mapped_column(JSONB, nullable=False)
    reason: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)

    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    expires_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), 
        server_default=text("now() + interval '24 hours'")
    )
    processed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)

    # Kapcsolatok meghatározása (String hivatkozással a körkörös import ellen)
    requester: Mapped["User"] = relationship("User", foreign_keys=[requester_id])
    approver: Mapped[Optional["User"]] = relationship("User", foreign_keys=[approver_id])