from shared.firebase import get_db
from settings.public_features_models import PublicFeaturesSettings, PublicFeaturesSettingsUpdate

COLLECTION = "admin_settings"
DOC_ID = "public_features"


def get_public_features() -> PublicFeaturesSettings:
    """Get public features settings from Firestore. Creates defaults if not found."""
    db = get_db()
    doc = db.collection(COLLECTION).document(DOC_ID).get()
    if doc.exists:
        return PublicFeaturesSettings(**doc.to_dict())
    defaults = PublicFeaturesSettings()
    db.collection(COLLECTION).document(DOC_ID).set(defaults.model_dump())
    return defaults


def update_public_features(data: PublicFeaturesSettingsUpdate) -> PublicFeaturesSettings:
    """Update public features settings. Only provided fields are updated."""
    db = get_db()
    doc_ref = db.collection(COLLECTION).document(DOC_ID)
    doc = doc_ref.get()

    existing = doc.to_dict() if doc.exists else PublicFeaturesSettings().model_dump()
    update_data = data.model_dump(exclude_none=True)
    existing.update(update_data)

    normalized = PublicFeaturesSettings(**existing)
    doc_ref.set(normalized.model_dump())
    return normalized
