import { Hono } from "hono";
import {
	getPopularItemsByTags,
	getPopularSetups,
	getRecentGlobalItems,
	getTrendingCategories,
} from "../services/discovery.service.ts";

type Env = { Variables: { db?: any } };

const app = new Hono<Env>();

app.get("/setups", async (c) => {
	const db = c.get("db");
	const limitParam = c.req.query("limit");
	const cursor = c.req.query("cursor");
	const limit = Math.min(limitParam ? parseInt(limitParam, 10) || 6 : 6, 50);
	const result = await getPopularSetups(db, limit, cursor);
	return c.json(result);
});

app.get("/items", async (c) => {
	const db = c.get("db");
	const limitParam = c.req.query("limit");
	const cursor = c.req.query("cursor");
	const limit = Math.min(limitParam ? parseInt(limitParam, 10) || 8 : 8, 50);
	const result = await getRecentGlobalItems(db, limit, cursor);
	return c.json(result);
});

app.get("/categories", async (c) => {
	const db = c.get("db");
	const limitParam = c.req.query("limit");
	const limit = Math.min(limitParam ? parseInt(limitParam, 10) || 12 : 12, 50);
	const result = await getTrendingCategories(db, limit);
	return c.json(result);
});

app.get("/popular-items", async (c) => {
	const db = c.get("db");
	const tagsParam = c.req.query("tags") || "";
	const limitParam = c.req.query("limit");
	const tagNames = tagsParam
		.split(",")
		.map((t) => t.trim())
		.filter(Boolean);
	const limit = limitParam ? Math.min(Number.parseInt(limitParam, 10), 50) : 24;

	if (tagNames.length === 0) {
		return c.json({ items: [] });
	}

	const results = await getPopularItemsByTags(db, tagNames, limit);
	return c.json({ items: results });
});

export { app as discoveryRoutes };
