# /opt/docker/dev/service_finder/backend/app/models/system.py
import uuid
from datetime import datetime
from typing import Optional
from sqlalchemy import String, Integer, Boolean, DateTime, text, UniqueConstraint, ForeignKey, Text
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.dialects.postgresql import JSONB, UUID
from sqlalchemy.sql import func
from app.db.base_class import Base

class SystemParameter(Base):
    """ Dinamikus konfigurációs motor (Global -> Org -> User). """
    __tablename__ = "system_parameters"
    __table_args__ = (
        UniqueConstraint('key', 'scope_level', 'scope_id', name='uix_param_scope'),
        {"extend_existing": True}
    )

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    key: Mapped[str] = mapped_column(String, index=True)
    category: Mapped[str] = mapped_column(String, server_default="general", index=True)
    value: Mapped[dict] = mapped_column(JSONB, nullable=False)
    
    scope_level: Mapped[str] = mapped_column(String(30), server_default=text("'global'"), index=True)
    scope_id: Mapped[Optional[str]] = mapped_column(String(50)) 
    
    is_active: Mapped[bool] = mapped_column(Boolean, default=True)
    description: Mapped[Optional[str]] = mapped_column(String)
    last_modified_by: Mapped[Optional[int]] = mapped_column(Integer, nullable=True)
    updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), onupdate=func.now(), server_default=func.now())

class InternalNotification(Base):
    """ 
    Belső értesítési központ. 
    Ezek az üzenetek várják a felhasználót belépéskor.
    """
    __tablename__ = "internal_notifications"
    __table_args__ = ({"schema": "data", "extend_existing": True})

    id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    user_id: Mapped[int] = mapped_column(ForeignKey("identity.users.id", ondelete="CASCADE"), nullable=False, index=True)
    
    title: Mapped[str] = mapped_column(String(255), nullable=False)
    message: Mapped[str] = mapped_column(Text, nullable=False)
    category: Mapped[str] = mapped_column(String(50), server_default="info") # insurance, mot, service, legal
    priority: Mapped[str] = mapped_column(String(20), server_default="medium") # low, medium, high, critical
    
    is_read: Mapped[bool] = mapped_column(Boolean, default=False, index=True)
    created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
    read_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    
    # Metaadatok a gyors eléréshez (melyik autó, melyik VIN)
    data: Mapped[Optional[dict]] = mapped_column(JSONB, nullable=True)