from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import List, Optional
from odoo.addons.fastapi.dependencies import odoo_env

router = APIRouter(tags=["products"])


class ProductResponse(BaseModel):
    uuid: str
    name: str
    category_id: int
    category_name: str
    terminus_schema_id: Optional[str] = None


@router.get("/products")
def get_products(env=Depends(odoo_env)) -> List[ProductResponse]:
    """Получить список всех товаров"""
    
    Product = env['products.product']
    products = Product.search([])
    
    result = []
    for product in products:
        result.append(ProductResponse(
            uuid=product.uuid,
            name=product.name,
            category_id=product.category_id.id if product.category_id else 0,
            category_name=product.category_name or '',
            terminus_schema_id=product.terminus_schema_id or None
        ))

    return result


@router.get("/products/{product_uuid}")
def get_product(product_uuid: str, env=Depends(odoo_env)) -> ProductResponse:
    """Получить товар по UUID"""
    
    Product = env['products.product']
    product = Product.search([('uuid', '=', product_uuid)], limit=1)
    
    if not product:
        raise HTTPException(status_code=404, detail=f"Product with UUID {product_uuid} not found")
    
    return ProductResponse(
        uuid=product.uuid,
        name=product.name,
        category_id=product.category_id.id if product.category_id else 0,
        category_name=product.category_name or '',
        terminus_schema_id=product.terminus_schema_id or None
    )