from pathlib import Path
from fastapi import APIRouter, Request
from fastapi.templating import Jinja2Templates
from app.db import fetch_all

router = APIRouter(prefix="/products", tags=["products"])
BASE_DIR = Path(__file__).resolve().parent.parent.parent
templates = Jinja2Templates(directory=str(BASE_DIR / "templates"))

def _iso_rows(rows: list) -> list:
    for row in rows:
        for key, val in list(row.items()):
            if hasattr(val, "isoformat"):
                row[key] = val.isoformat()
    return rows

@router.get("")
async def products_page(request: Request):
    rows = []
    try:
        rows = _iso_rows(fetch_all(
            """SELECT p.id, p.name, p.status, p.margin_pct, p.moq, p.shelf_target, p.launch_date, p.created_at,
                      c.name AS client_name
               FROM products p LEFT JOIN clients c ON c.id = p.client_id
               ORDER BY p.created_at DESC LIMIT 200"""
        ))
    except Exception:
        rows = []
    return templates.TemplateResponse("products.html", {"request": request, "page_title": "Products", "products": rows})
