from fastapi import APIRouter, Depends, Request
from ...core.database import get_db, get_system_db, _has_split_databases
from ...core.permission import get_current_user, is_admin_role
import uuid
from ...utils.request_utils import safe_json

router = APIRouter()


async def _system_db():
    """Dependency: system.db when split databases exist, otherwise fallback to get_db()"""
    _db_gen = get_system_db() if _has_split_databases() else get_db()
    async for conn, cur in _db_gen:
        yield conn, cur


@router.get("")
async def get_welcome_message(request: Request, db=Depends(_system_db)):
    conn, cur = db
    try:
        await cur.execute(
            "SELECT id, title, content, status, created_at as createdAt, updated_at as updatedAt FROM welcome_messages WHERE status = 1 ORDER BY created_at DESC LIMIT 1"
        )
        row = await cur.fetchone()
        return dict(row) if row else None
    except Exception:
        return None


@router.post("")
async def create_welcome_message(request: Request, db=Depends(_system_db)):
    current_user = get_current_user(request)
    if not current_user or not is_admin_role(current_user["role"]):
        return {"error": "无权限", "detail": "admin required"}

    conn, cur = db
    body = await safe_json(request)
    content = body.get("content")
    if not content:
        return {"error": "内容不能为空", "detail": "content required"}

    title = body.get("title", "你好，欢迎回来！")
    msg_id = str(uuid.uuid4())
    created_by = current_user.get("userId")

    try:
        await cur.execute("UPDATE welcome_messages SET status = 0 WHERE status = 1")
        await cur.execute(
            "INSERT INTO welcome_messages (id, title, content, status, created_by) VALUES (%s, %s, %s, 1, %s)",
            (msg_id, title, content, created_by),
        )
        return {"id": msg_id, "title": title, "content": content, "status": 1}
    except Exception as e:
        if "1146" in str(e) or "doesn't exist" in str(e):
            return {"error": "欢迎消息表尚未创建", "detail": "table not created yet"}
        raise
