from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, status from sqlmodel import select from sqlmodel.ext.asyncio.session import AsyncSession from typing import List from uuid import UUID from datetime import datetime from app.core.database import get_session from app.models.product import Product from app.models.user import User from app.api.deps import get_current_user from app.services.ai_memory_manager import get_memory_manager from pydantic import BaseModel from app.models.tenant import Tenant router = APIRouter(prefix="/products", tags=["Products"]) # ============================================================================ # Request/Response Models # ============================================================================ class ProductCreate(BaseModel): """Schema for creating a new product.""" name: str description: str | None = None price: float currency: str = "USD" category: str image_url: str | None = None # Legacy: single image image_urls: List[str] | None = None # NEW: Multiple images in_stock: bool = True class ProductUpdate(BaseModel): """Schema for updating an existing product.""" name: str | None = None description: str | None = None price: float | None = None currency: str | None = None category: str | None = None image_url: str | None = None # Legacy: single image image_urls: List[str] | None = None # NEW: Multiple images in_stock: bool | None = None class ProductResponse(BaseModel): """Schema for product response.""" id: UUID tenant_id: UUID name: str description: str | None price: float currency: str category: str image_url: str | None # Legacy: single image image_urls: List[str] | None # NEW: Multiple images in_stock: bool created_at: datetime updated_at: datetime class Config: from_attributes = True # ============================================================================ # Endpoints # ============================================================================ @router.get("/", response_model=List[ProductResponse]) async def get_products( session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Get all products for the current tenant. """ statement = select(Product).where(Product.tenant_id == current_user.tenant_id) result = await session.execute(statement) products = result.scalars().all() return products @router.post("/", response_model=ProductResponse, status_code=status.HTTP_201_CREATED) async def create_product( product_data: ProductCreate, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Create a new product for the current tenant. """ product = Product( **product_data.model_dump(), tenant_id=current_user.tenant_id ) session.add(product) await session.commit() await session.refresh(product) # SIGNAL: Invalidate AI Memory tenant = await session.get(Tenant, current_user.tenant_id) if tenant: await get_memory_manager().invalidate_memory(session, tenant) return product @router.get("/{product_id}", response_model=ProductResponse) async def get_product( product_id: UUID, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Get a specific product by ID. """ statement = select(Product).where( Product.id == product_id, Product.tenant_id == current_user.tenant_id ) result = await session.execute(statement) product = result.scalar_one_or_none() if not product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found" ) return product @router.patch("/{product_id}", response_model=ProductResponse) async def update_product( product_id: UUID, product_data: ProductUpdate, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Update an existing product. """ statement = select(Product).where( Product.id == product_id, Product.tenant_id == current_user.tenant_id ) result = await session.execute(statement) product = result.scalar_one_or_none() if not product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found" ) # Update only provided fields update_data = product_data.model_dump(exclude_unset=True) for field, value in update_data.items(): setattr(product, field, value) product.updated_at = datetime.utcnow() session.add(product) await session.commit() await session.refresh(product) # SIGNAL: Invalidate AI Memory tenant = await session.get(Tenant, current_user.tenant_id) if tenant: await get_memory_manager().invalidate_memory(session, tenant) return product @router.delete("/{product_id}", status_code=status.HTTP_204_NO_CONTENT) async def delete_product( product_id: UUID, session: AsyncSession = Depends(get_session), current_user: User = Depends(get_current_user) ): """ Delete a product. """ statement = select(Product).where( Product.id == product_id, Product.tenant_id == current_user.tenant_id ) result = await session.execute(statement) product = result.scalar_one_or_none() if not product: raise HTTPException( status_code=status.HTTP_404_NOT_FOUND, detail="Product not found" ) await session.delete(product) await session.commit() # SIGNAL: Invalidate AI Memory tenant = await session.get(Tenant, current_user.tenant_id) if tenant: await get_memory_manager().invalidate_memory(session, tenant) return None @router.post("/upload-image") async def upload_product_image( file: UploadFile = File(...), current_user: User = Depends(get_current_user) ): """ Upload a product image. Returns the URL of the uploaded image. For now, returns a placeholder. In production, integrate with: - AWS S3 - Cloudinary - Supabase Storage """ # 1. Initialize Supabase from app.core.supabase import supabase_client if not supabase_client: raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, detail="Supabase Storage not configured" ) # 2. Sanitize filename & Rename to avoid collisions # Format: {tenant_id}/{timestamp}_{safe_filename} import re import time timestamp = int(time.time()) safe_filename = re.sub(r'[^a-zA-Z0-9_\-\.]', '_', file.filename) if len(safe_filename) > 50: safe_filename = safe_filename[-50:] # Tenant isolation folder storage_path = f"{current_user.tenant_id}/{timestamp}_{safe_filename}" # 3. Read file content file_content = await file.read() try: # 4. Upload to Supabase 'products' bucket res = supabase_client.storage.from_("products").upload( path=storage_path, file=file_content, file_options={"content-type": file.content_type} ) # 5. Get Public URL public_url = supabase_client.storage.from_("products").get_public_url(storage_path) return { "url": public_url, "filename": safe_filename, "content_type": file.content_type } except Exception as e: error_msg = str(e) print(f"❌ Storage Upload Error: {error_msg}") # Check for common Supabase Storage errors if "Bucket not found" in error_msg: detail = "Storage bucket 'products' not found. Please create it in Supabase Dashboard." elif "new row violates row-level security policy" in error_msg: detail = "Storage permission denied. Check RLS policies on 'products' bucket." else: detail = f"Upload failed: {error_msg}" raise HTTPException( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=detail )