"""
会员生日手动补录路由。

- POST /api/member-birthday — 助教提交会员生日（UPSERT）
"""

import logging

from fastapi import APIRouter, HTTPException, status

from app.database import get_connection
from app.schemas.member_birthday import MemberBirthdaySubmit

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api", tags=["会员生日"])


@router.post("/member-birthday")
async def submit_member_birthday(body: MemberBirthdaySubmit):
    """
    助教提交会员生日（UPSERT）。

    同一 (member_id, assistant_id) 组合重复提交时，
    更新 birthday_value 和 recorded_at，保留其他助教的记录。
    """
    sql = """
        INSERT INTO member_birthday_manual
            (member_id, birthday_value, recorded_by_assistant_id, recorded_by_name, site_id)
        VALUES (%s, %s, %s, %s, %s)
        ON CONFLICT (member_id, recorded_by_assistant_id)
        DO UPDATE SET
            birthday_value = EXCLUDED.birthday_value,
            recorded_at    = NOW()
    """
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(sql, (
                body.member_id,
                body.birthday_value,
                body.assistant_id,
                body.assistant_name,
                body.site_id,
            ))
        conn.commit()
    except Exception:
        conn.rollback()
        logger.exception("会员生日 UPSERT 失败: member_id=%s", body.member_id)
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="生日提交失败，请稍后重试",
        )
    finally:
        conn.close()

    return {"status": "ok"}
