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

router = APIRouter(prefix="/suppliers", tags=["suppliers"])
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 suppliers_page(request: Request):
    rows = []
    try:
        rows = _iso_rows(fetch_all(
            """SELECT id, name, country, category, moq, lead_time_days, rating, contact, created_at
               FROM suppliers ORDER BY rating DESC NULLS LAST, name ASC LIMIT 200"""
        ))
    except Exception:
        rows = []
    return templates.TemplateResponse("suppliers.html", {"request": request, "page_title": "Suppliers", "suppliers": rows})
