"""后台会员与消费口径配置。"""
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import require_role
from app.database import get_db
from app.models.user import User
from app.schemas.common import ApiResponse
from app.schemas.membership import (
    MemberLevelResponse,
    SpendEventTypeConfigResponse,
    SpendEventTypeConfigUpdate,
)
from app.services import membership_service, spend_service

router = APIRouter()
_admin = require_role("admin", "super_admin")


@router.get("/levels", response_model=ApiResponse)
async def list_member_levels(
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    levels = await membership_service.get_member_levels(db)
    return ApiResponse(data=[MemberLevelResponse.model_validate(level) for level in levels])


@router.get("/spend-event-types", response_model=ApiResponse)
async def list_spend_event_types(
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    configs = await spend_service.get_spend_event_type_configs(db)
    return ApiResponse(data=[SpendEventTypeConfigResponse.model_validate(config) for config in configs])


@router.patch("/spend-event-types/{code}", response_model=ApiResponse)
async def update_spend_event_type(
    code: str,
    body: SpendEventTypeConfigUpdate,
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    config, changed = await spend_service.set_spend_event_type_enabled(db, code, body.enabled)
    if not config:
        raise HTTPException(status_code=404, detail="消费类型不存在")

    recalculated_users = 0
    if changed:
        recalculated_users = await spend_service.recalculate_all_membership_spent(db)

    return ApiResponse(data={
        "config": SpendEventTypeConfigResponse.model_validate(config),
        "recalculated_users": recalculated_users,
    })


@router.post("/spend/recalculate", response_model=ApiResponse)
async def recalculate_spend(
    db: AsyncSession = Depends(get_db),
    _: User = Depends(_admin),
):
    count = await spend_service.recalculate_all_membership_spent(db)
    return ApiResponse(data={"recalculated_users": count})
