import uuid
import enum
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey, JSON, Numeric, text, Enum, BigInteger, UniqueConstraint
from sqlalchemy.orm import relationship
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.sql import func
from app.db.base_class import Base

class UserRole(str, enum.Enum):
    superadmin = "superadmin"
    admin = "admin"
    user = "user"
    service = "service"
    fleet_manager = "fleet_manager"
    driver = "driver"

class Person(Base):
    """
    Természetes személy identitása. 
    A bot által talált személyek is ide kerülnek (is_ghost=True).
    Azonosítás: Név + Anyja neve + Születési adatok alapján.
    """
    __tablename__ = "persons"
    __table_args__ = {"schema": "data"}
    
    id = Column(BigInteger, primary_key=True, index=True)
    id_uuid = Column(PG_UUID(as_uuid=True), default=uuid.uuid4, unique=True, nullable=False)
    address_id = Column(PG_UUID(as_uuid=True), ForeignKey("data.addresses.id"), nullable=True)
    
    last_name = Column(String, nullable=False)
    first_name = Column(String, nullable=False)
    phone = Column(String, nullable=True)
    
    # --- TERMÉSZETES AZONOSÍTÓK (Azonosításhoz, nem publikus) ---
    mothers_last_name = Column(String)
    mothers_first_name = Column(String)
    birth_place = Column(String)
    birth_date = Column(DateTime)
    
    identity_docs = Column(JSON, server_default=text("'{}'::jsonb"))
    ice_contact = Column(JSON, server_default=text("'{}'::jsonb"))
    
    is_active = Column(Boolean, default=False, nullable=False)
    is_ghost = Column(Boolean, default=True, nullable=False) # Bot találta = True, Regisztrált = False
    
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    users = relationship("User", back_populates="person")
    memberships = relationship("OrganizationMember", back_populates="person")

class User(Base):
    __tablename__ = "users"
    __table_args__ = {"schema": "data"}
    
    id = Column(Integer, primary_key=True, index=True)
    email = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=True)
    role = Column(Enum(UserRole), default=UserRole.user)
    is_active = Column(Boolean, default=False)
    is_deleted = Column(Boolean, default=False)
    
    person_id = Column(BigInteger, ForeignKey("data.persons.id"), nullable=True)
    folder_slug = Column(String(12), unique=True, index=True)
    
    refresh_token_hash = Column(String(255), nullable=True)
    two_factor_secret = Column(String(100), nullable=True)
    two_factor_enabled = Column(Boolean, default=False)
    
    preferred_language = Column(String(5), server_default="hu")
    region_code = Column(String(5), server_default="HU")
    preferred_currency = Column(String(3), server_default="HUF")
    
    scope_level = Column(String(30), server_default="individual")
    scope_id = Column(String(50))
    custom_permissions = Column(JSON, server_default=text("'{}'::jsonb"))
    
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    person = relationship("Person", back_populates="users")
    wallet = relationship("Wallet", back_populates="user", uselist=False)
    stats = relationship("UserStats", back_populates="user", uselist=False)
    ownership_history = relationship("VehicleOwnership", back_populates="user")
    owned_organizations = relationship("Organization", back_populates="owner")
    social_accounts = relationship("SocialAccount", back_populates="user", cascade="all, delete-orphan")

class Wallet(Base):
    __tablename__ = "wallets"; __table_args__ = {"schema": "data"}
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("data.users.id"), unique=True)
    coin_balance = Column(Numeric(18, 2), default=0.00); credit_balance = Column(Numeric(18, 2), default=0.00); currency = Column(String(3), default="HUF")
    user = relationship("User", back_populates="wallet")

class VerificationToken(Base):
    __tablename__ = "verification_tokens"; __table_args__ = {"schema": "data"}
    id = Column(Integer, primary_key=True, index=True)
    token = Column(PG_UUID(as_uuid=True), default=uuid.uuid4, unique=True, nullable=False)
    user_id = Column(Integer, ForeignKey("data.users.id", ondelete="CASCADE"), nullable=False)
    token_type = Column(String(20), nullable=False); created_at = Column(DateTime(timezone=True), server_default=func.now())
    expires_at = Column(DateTime(timezone=True), nullable=False); is_used = Column(Boolean, default=False)

class SocialAccount(Base):
    __tablename__ = "social_accounts"
    __table_args__ = (UniqueConstraint('provider', 'social_id', name='uix_social_provider_id'), {"schema": "data"})
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("data.users.id", ondelete="CASCADE"), nullable=False)
    provider = Column(String(50), nullable=False); social_id = Column(String(255), nullable=False, index=True); email = Column(String(255), nullable=False)
    extra_data = Column(JSON, server_default=text("'{}'::jsonb")); created_at = Column(DateTime(timezone=True), server_default=func.now())
    user = relationship("User", back_populates="social_accounts")