import { Hono } from "hono";
import { parseId } from "../lib/params.ts";
import {
	getGlobalItemWithOwnerCount,
	searchGlobalItems,
} from "../services/global-item.service.ts";

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

const app = new Hono<Env>();

app.get("/", async (c) => {
	const db = c.get("db");
	const q = c.req.query("q");
	const tagsParam = c.req.query("tags");
	const tagNames = tagsParam
		? tagsParam
				.split(",")
				.map((t) => t.trim())
				.filter(Boolean)
		: undefined;
	const items = await searchGlobalItems(db, q || undefined, tagNames);
	return c.json(items);
});

app.get("/:id", async (c) => {
	const db = c.get("db");
	const id = parseId(c.req.param("id"));
	if (!id) return c.json({ error: "Invalid global item ID" }, 400);
	const item = await getGlobalItemWithOwnerCount(db, id);
	if (!item) return c.json({ error: "Global item not found" }, 404);
	return c.json(item);
});

export { app as globalItemRoutes };
