# backend/app/plugins/weighed_goods/router.py
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession

from app.api.deps import get_db, get_admin_user
from app.core.models.user import User
from app.core.models.product import Product
from app.core.services.plugin_helper import require_plugin


async def _require_weighed_goods(db: AsyncSession = Depends(get_db)) -> None:
    """插件停用时返回 503"""
    await require_plugin("weighed_goods", db)


router = APIRouter(prefix="/admin/weighed-goods", tags=["称重商品"], dependencies=[Depends(_require_weighed_goods)])


class WeighedFlagIn(BaseModel):
    soldByWeight: bool


@router.patch("/products/{product_id}")
async def set_sold_by_weight(
    product_id: int,
    body: WeighedFlagIn,
    db: AsyncSession = Depends(get_db),
    user: User = Depends(get_admin_user),
):
    r = await db.execute(
        select(Product).where(
            Product.id == product_id,
            Product.tenant_id == user.tenant_id,
        )
    )
    product = r.scalar_one_or_none()
    if product is None:
        raise HTTPException(status_code=404, detail="商品不存在")
    product.set_attribute("sold_by_weight", body.soldByWeight)
    await db.commit()
    return {"id": product.id, "soldByWeight": body.soldByWeight}
