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

from app.dependencies import get_db, get_admin_user, get_current_user
from app.models.user import User
from app.models.recharge_package import RechargePackage
from app.schemas.recharge_package import (
    RechargePackageCreate,
    RechargePackageUpdate,
    RechargePackageOut,
)
from app.utils.id_gen import generate_id

router = APIRouter(tags=["recharge-packages"])


def _to_out(pkg: RechargePackage) -> dict:
    return {
        "id": pkg.id,
        "name": pkg.name,
        "credits": round(pkg.credits, 2),
        "price": round(pkg.price, 2),
        "bonus_credits": round(pkg.bonus_credits, 2),
        "total_credits": round(pkg.credits + pkg.bonus_credits, 2),
        "description": pkg.description,
        "package_type": pkg.package_type,
        "is_gift": pkg.is_gift,
        "is_active": pkg.is_active,
        "sort_order": pkg.sort_order,
    }


@router.get("/recharge-packages")
async def list_active_packages(
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """Public: list active recharge packages."""
    result = await db.execute(
        select(RechargePackage)
        .where(RechargePackage.is_active == True)
        .order_by(RechargePackage.sort_order)
    )
    return [_to_out(p) for p in result.scalars().all()]


@router.get("/admin/recharge-packages")
async def admin_list_packages(
    _admin=Depends(get_admin_user),
    db: AsyncSession = Depends(get_db),
):
    """Admin: list all packages."""
    result = await db.execute(
        select(RechargePackage).order_by(RechargePackage.sort_order)
    )
    return [_to_out(p) for p in result.scalars().all()]


@router.post("/admin/recharge-packages")
async def create_package(
    data: RechargePackageCreate,
    _admin=Depends(get_admin_user),
    db: AsyncSession = Depends(get_db),
):
    pkg = RechargePackage(id=generate_id(), **data.model_dump())
    db.add(pkg)
    await db.flush()
    return _to_out(pkg)


@router.put("/admin/recharge-packages/{pkg_id}")
async def update_package(
    pkg_id: str,
    data: RechargePackageUpdate,
    _admin=Depends(get_admin_user),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(RechargePackage).where(RechargePackage.id == pkg_id).limit(1)
    )
    pkg = result.scalar_one_or_none()
    if not pkg:
        raise HTTPException(status_code=404, detail="套餐不存在")
    for k, v in data.model_dump(exclude_unset=True).items():
        setattr(pkg, k, v)
    await db.flush()
    return _to_out(pkg)


@router.delete("/admin/recharge-packages/{pkg_id}")
async def delete_package(
    pkg_id: str,
    _admin=Depends(get_admin_user),
    db: AsyncSession = Depends(get_db),
):
    result = await db.execute(
        select(RechargePackage).where(RechargePackage.id == pkg_id).limit(1)
    )
    pkg = result.scalar_one_or_none()
    if not pkg:
        raise HTTPException(status_code=404, detail="套餐不存在")
    await db.delete(pkg)
    await db.flush()
    return {"ok": True}
