"""前台货币 API（无需登录）

路由：
  GET  /store/currencies          获取该租户已启用的货币列表（含基准货币）
  POST /store/currencies/convert  金额换算（前台展示用）
"""
from decimal import Decimal

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

from app.api.deps import get_db, get_tenant_by_domain
from app.core.services.currency_service import CurrencyService

router = APIRouter(prefix="/store", tags=["前台货币"])



class StoreCurrencyOut(BaseModel):
    code: str
    name: str
    symbol: str
    exchange_rate: float
    is_default: bool


class StoreConvertIn(BaseModel):
    amount: Decimal = Field(..., gt=0)
    from_code: str = Field(..., min_length=3, max_length=3)
    to_code: str = Field(..., min_length=3, max_length=3)


@router.get("/currencies", response_model=list[StoreCurrencyOut], summary="已启用货币列表")
async def list_store_currencies(
    db: AsyncSession = Depends(get_db),
    tid: int = Depends(get_tenant_by_domain),
):
    currencies = await CurrencyService.get_active(db, tid)
    return [
        StoreCurrencyOut(
            code=c.code,
            name=c.name,
            symbol=c.symbol,
            exchange_rate=float(c.exchange_rate),
            is_default=bool(c.is_default),
        )
        for c in currencies
    ]


@router.post("/currencies/convert", summary="前台金额换算")
async def store_convert(
    body: StoreConvertIn,
    db: AsyncSession = Depends(get_db),
    tid: int = Depends(get_tenant_by_domain),
):
    from_cur = await CurrencyService.get_by_code(db, tid, body.from_code.upper())
    to_cur = await CurrencyService.get_by_code(db, tid, body.to_code.upper())

    if not from_cur or not to_cur:
        raise HTTPException(status_code=404, detail="货币不存在或未启用")

    result = CurrencyService.convert_amount(
        body.amount, from_cur.exchange_rate, to_cur.exchange_rate
    )
    return {
        "from_code": from_cur.code,
        "from_symbol": from_cur.symbol,
        "to_code": to_cur.code,
        "to_symbol": to_cur.symbol,
        "from_amount": float(body.amount),
        "to_amount": float(result),
    }
