/* =====================================================================
   routes/bestseller.js — GET /api/bestseller. 1:1 portiert aus functions/api/bestseller.js,
   D1-Abfrage auf synchrones better-sqlite3 umgestellt.
   ===================================================================== */

import { Router } from "express";
import { db } from "../db.js";

export const bestsellerRouter = Router();

bestsellerRouter.get("/api/bestseller", (req, res) => {
  try {
    const results = db
      .prepare(
        `SELECT oi.produkt_slug AS slug, SUM(oi.menge) AS verkauft
         FROM order_items oi
         JOIN orders o ON o.id = oi.order_id
         WHERE o.status NOT IN ('storniert', 'zahlungOffen') AND oi.gratis = 0
         GROUP BY oi.produkt_slug
         ORDER BY verkauft DESC, slug ASC
         LIMIT 6`
      )
      .all();
    return res.json({ ok: true, slugs: results.map((r) => r.slug) });
  } catch {
    return res.json({ ok: true, slugs: [] });
  }
});
