from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.deps import get_current_user
from app.database import get_db
from app.models.user import User
from app.schemas.common import ApiResponse
from app.schemas.membership import (
    MemberLevelResponse,
    PointLogResponse,
    UserMembershipResponse,
)
from app.services import membership_service

router = APIRouter()


@router.get("/levels", response_model=ApiResponse)
async def get_member_levels(db: AsyncSession = Depends(get_db)):
    """获取所有会员等级配置"""
    levels = await membership_service.get_member_levels(db)
    return ApiResponse(data=[MemberLevelResponse.model_validate(l) for l in levels])


@router.get("/me", response_model=ApiResponse)
async def get_my_membership(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """获取当前用户的会员信息"""
    membership = await membership_service.get_or_create_membership(db, current_user.id)
    data = UserMembershipResponse.model_validate(membership).model_dump()
    current_quarter_self_spent = await membership_service.get_current_quarter_self_spent(db, current_user.id)
    data["current_quarter_self_spent"] = current_quarter_self_spent
    data["current_quarter_spent"] = current_quarter_self_spent
    if membership.member_level:
        data["commission_rate"] = membership.member_level.commission_rate
    return ApiResponse(data=data)


@router.get("/points/logs", response_model=ApiResponse)
async def get_point_logs(
    limit: int = 20,
    offset: int = 0,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """获取当前用户的积分流水"""
    logs = await membership_service.get_point_logs(db, current_user.id, limit, offset)
    return ApiResponse(data=[PointLogResponse.model_validate(log) for log in logs])
