"""
Database models for the sim-search API.

This module defines the SQLAlchemy ORM models for the database.
"""

import datetime
import uuid
from typing import Dict, Any, List

from sqlalchemy import Column, String, Boolean, ForeignKey, DateTime, Integer, JSON, Text
from sqlalchemy.orm import relationship

from app.db.session import Base


def generate_uuid() -> str:
    """Generate a UUID string."""
    return str(uuid.uuid4())


class User(Base):
    """User model."""
    
    __tablename__ = "users"
    
    id = Column(String, primary_key=True, index=True, default=generate_uuid)
    email = Column(String, unique=True, index=True, nullable=False)
    hashed_password = Column(String, nullable=False)
    full_name = Column(String, nullable=True)
    is_active = Column(Boolean, default=True)
    is_superuser = Column(Boolean, default=False)
    
    searches = relationship("Search", back_populates="user")
    reports = relationship("Report", back_populates="user")


class Search(Base):
    """Search model."""
    
    __tablename__ = "searches"
    
    id = Column(String, primary_key=True, index=True, default=generate_uuid)
    user_id = Column(String, ForeignKey("users.id"))
    query = Column(String, nullable=False)
    enhanced_query = Column(String, nullable=True)
    query_type = Column(String, nullable=True)
    engines = Column(String, nullable=True)  # Comma-separated list
    results_count = Column(Integer, default=0)
    results = Column(JSON, nullable=True)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    
    user = relationship("User", back_populates="searches")
    reports = relationship("Report", back_populates="search")


class Report(Base):
    """Report model."""
    
    __tablename__ = "reports"
    
    id = Column(String, primary_key=True, index=True, default=generate_uuid)
    user_id = Column(String, ForeignKey("users.id"))
    search_id = Column(String, ForeignKey("searches.id"), nullable=True)
    title = Column(String, nullable=False)
    content = Column(Text, nullable=False)
    detail_level = Column(String, nullable=False, default="standard")
    query_type = Column(String, nullable=True)
    model_used = Column(String, nullable=True)
    created_at = Column(DateTime, default=datetime.datetime.utcnow)
    updated_at = Column(DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow)
    
    user = relationship("User", back_populates="reports")
    search = relationship("Search", back_populates="reports")
