from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

from app.core.database import get_db
from app.core.deps import get_current_user
from app.models.user import SystemSettings, User
from app.schemas import AppFeaturesOut, PublicSettingsOut

router = APIRouter(prefix="/settings", tags=["settings"])


def get_or_create_settings(db: Session) -> SystemSettings:
    row = db.get(SystemSettings, 1)
    if row is None:
        row = SystemSettings(id=1, registration_enabled=True)
        db.add(row)
        db.commit()
        db.refresh(row)
    return row


@router.get("/public", response_model=PublicSettingsOut)
def public_settings(db: Session = Depends(get_db)):
    row = get_or_create_settings(db)
    return PublicSettingsOut(registration_enabled=row.registration_enabled)


@router.get("/app-features", response_model=AppFeaturesOut)
def app_features(
    db: Session = Depends(get_db),
    _: User = Depends(get_current_user),
):
    row = get_or_create_settings(db)
    return AppFeaturesOut(ai_review_enabled=getattr(row, "ai_review_enabled", True))
