"""收藏夹 API（小程序）"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete, Column, BigInteger, Integer, UniqueConstraint, DateTime
from sqlalchemy.sql import func

from app.api.deps import get_db
from app.api.routers.store.auth import get_current_customer
from app.core.models.base import Base
from app.core.models.customer import Customer
from app.core.models.product import Product
from app.schemas.product import ProductListOut


class CustomerWishlist(Base):
    __tablename__ = "customer_wishlists"
    __table_args__ = (
        UniqueConstraint("customer_id", "product_id", name="uk_wishlist_customer_product"),
        {"mysql_engine": "InnoDB", "mysql_charset": "utf8mb4"},
    )

    id = Column(BigInteger, primary_key=True, autoincrement=True)
    customer_id = Column(BigInteger, nullable=False, index=True)
    product_id = Column(BigInteger, nullable=False, index=True)
    tenant_id = Column(Integer, nullable=False, index=True)
    created_at = Column(DateTime, server_default=func.now(), nullable=False)


router = APIRouter(prefix="/store/wishlist", tags=["收藏夹"])


@router.get("", summary="获取收藏列表")
async def list_wishlist(
    customer: Customer = Depends(get_current_customer),
    db: AsyncSession = Depends(get_db),
):
    rows = await db.execute(
        select(CustomerWishlist).where(
            CustomerWishlist.customer_id == customer.id,
            CustomerWishlist.tenant_id == customer.tenant_id,
        ).order_by(CustomerWishlist.id.desc())
    )
    items = rows.scalars().all()
    if not items:
        return {"items": []}

    product_ids = [i.product_id for i in items]
    prods = await db.execute(
        select(Product).where(
            Product.id.in_(product_ids),
            Product.tenant_id == customer.tenant_id,
        )
    )
    prod_map = {p.id: p for p in prods.scalars().all()}

    result = []
    for item in items:
        p = prod_map.get(item.product_id)
        if p:
            result.append({
                "product_id": p.id,
                "product": {
                    "id": p.id,
                    "name": p.name,
                    "slug": p.slug,
                    "base_price": float(p.base_price or 0),
                    "cover_url": p.cover_url,
                },
            })
    return {"items": result}


class WishlistAddIn(BaseModel):
    product_id: int


@router.post("", summary="添加收藏", status_code=201)
async def add_wishlist(
    body: WishlistAddIn,
    customer: Customer = Depends(get_current_customer),
    db: AsyncSession = Depends(get_db),
):
    prod = await db.get(Product, body.product_id)
    if not prod or prod.tenant_id != customer.tenant_id:
        raise HTTPException(status_code=404, detail="商品不存在")

    existing = await db.execute(
        select(CustomerWishlist).where(
            CustomerWishlist.customer_id == customer.id,
            CustomerWishlist.product_id == body.product_id,
        )
    )
    if existing.scalar_one_or_none():
        return {"message": "already in wishlist"}

    db.add(CustomerWishlist(
        customer_id=customer.id,
        product_id=body.product_id,
        tenant_id=customer.tenant_id,
    ))
    await db.commit()
    return {"message": "added"}


@router.post("/{product_id}/remove", summary="取消收藏")
async def remove_wishlist(
    product_id: int,
    customer: Customer = Depends(get_current_customer),
    db: AsyncSession = Depends(get_db),
):
    await db.execute(
        delete(CustomerWishlist).where(
            CustomerWishlist.customer_id == customer.id,
            CustomerWishlist.product_id == product_id,
        )
    )
    await db.commit()
    return {"message": "removed"}
