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

from app.api.deps import get_db, get_admin_user
from app.core.models.product import ProductImage, Product
from app.schemas.image import ImageOut, ImageCreate, ImageUpdate
from app.core.models.user import User

router = APIRouter(prefix="/products/{product_id}/images", tags=["商品图片"])


async def get_product_or_404(db: AsyncSession, product_id: int, admin_user: User):
    result = await db.execute(
        select(Product).where(Product.id == product_id, Product.tenant_id == admin_user.tenant_id)
    )
    product = result.scalar_one_or_none()
    if not product:
        raise HTTPException(status_code=404, detail="商品不存在")
    return product


@router.get("", response_model=list[ImageOut])
async def list_images(
    product_id: int,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    """列出商品所有图片"""
    await get_product_or_404(db, product_id, admin_user)
    result = await db.execute(
        select(ProductImage)
        .where(ProductImage.product_id == product_id)
        .order_by(ProductImage.sort_order, ProductImage.id)
    )
    images = result.scalars().all()
    return images


@router.post("", response_model=ImageOut, status_code=status.HTTP_201_CREATED)
async def upload_image(
    product_id: int,
    body: ImageCreate,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    """上传商品图片"""
    product = await get_product_or_404(db, product_id, admin_user)

    if body.is_primary:
        await db.execute(
            ProductImage.__table__.update()
            .where(ProductImage.product_id == product_id, ProductImage.is_primary == 1)
            .values(is_primary=0)
        )

    image = ProductImage(
        product_id=product_id,
        tenant_id=admin_user.tenant_id,
        url=body.url,
        alt_text=body.alt_text,
        sort_order=body.sort_order,
        is_primary=1 if body.is_primary else 0,
    )
    db.add(image)
    await db.commit()
    await db.refresh(image)
    return image


@router.put("/{image_id}", response_model=ImageOut)
async def update_image(
    product_id: int,
    image_id: int,
    body: ImageUpdate,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    """更新图片信息"""
    await get_product_or_404(db, product_id, admin_user)
    result = await db.execute(
        select(ProductImage).where(
            ProductImage.id == image_id, ProductImage.product_id == product_id
        )
    )
    image = result.scalar_one_or_none()
    if not image:
        raise HTTPException(status_code=404, detail="图片不存在")

    if body.is_primary:
        await db.execute(
            ProductImage.__table__.update()
            .where(ProductImage.product_id == product_id, ProductImage.is_primary == 1)
            .values(is_primary=0)
        )

    update_data = body.model_dump(exclude_unset=True)
    for k, v in update_data.items():
        if k == "is_primary":
            setattr(image, k, 1 if v else 0)
        else:
            setattr(image, k, v)

    await db.commit()
    await db.refresh(image)
    return image


@router.delete("/{image_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_image(
    product_id: int,
    image_id: int,
    db: AsyncSession = Depends(get_db),
    admin_user: User = Depends(get_admin_user),
):
    """删除图片"""
    await get_product_or_404(db, product_id, admin_user)
    result = await db.execute(
        select(ProductImage).where(
            ProductImage.id == image_id, ProductImage.product_id == product_id
        )
    )
    image = result.scalar_one_or_none()
    if not image:
        raise HTTPException(status_code=404, detail="图片不存在")

    await db.delete(image)
    await db.commit()