import uuid

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

from app.api.deps import get_current_user
from app.database import get_db
from app.models.user import User
from app.schemas.subscription import (
    PlanDetail,
    SubscribeRequest,
    SubscriptionHistoryResponse,
    SubscriptionResponse,
)
from app.services.subscription import (
    cancel_subscription,
    get_current_subscription,
    get_plans,
    get_subscription_history,
    subscribe,
)

router = APIRouter(prefix="/api/v1/subscriptions", tags=["subscriptions"])


@router.get("/plans", response_model=list[PlanDetail])
async def list_plans():
    return get_plans()


@router.get("/current", response_model=SubscriptionResponse)
async def read_current_subscription(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    sub = await get_current_subscription(db, current_user.id)
    if sub is None:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="暂无订阅记录",
        )
    return sub


@router.post("/subscribe", response_model=SubscriptionResponse, status_code=status.HTTP_201_CREATED)
async def create_subscription(
    request: SubscribeRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    try:
        sub = await subscribe(db, current_user.id, request.plan)
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e),
        )
    return sub


@router.post("/cancel")
async def cancel_current_subscription(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    result = await cancel_subscription(db, current_user.id)
    return result


@router.get("/history", response_model=SubscriptionHistoryResponse)
async def read_subscription_history(
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
):
    items = await get_subscription_history(db, current_user.id)
    return {"items": items, "total": len(items)}
