import json

from fastapi import APIRouter, HTTPException

from app.db.database import SessionLocal
from app.db.models import Tenant
from app.schemas.tenant import WidgetConfig

router = APIRouter()


@router.get("/widget/{tenant_id}/config", response_model=WidgetConfig)
def get_widget_config(tenant_id: str) -> WidgetConfig:
    db = SessionLocal()
    try:
        tenant = db.query(Tenant).filter(Tenant.id == tenant_id).first()
    finally:
        db.close()
    if not tenant:
        raise HTTPException(status_code=404, detail="Unknown tenant")
    return WidgetConfig(
        tenant_id=tenant.id,
        bot_name=tenant.bot_name,
        welcome_message=tenant.welcome_message,
        primary_color=tenant.primary_color,
        position=tenant.position,
        quick_actions=json.loads(tenant.quick_actions),
        vertical=tenant.vertical,
    )
