import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
	bulkUpsertGlobalItemsSchema,
	upsertGlobalItemSchema,
} from "../../shared/schemas.ts";
import { parseId } from "../lib/params.ts";
import {
	bulkUpsertGlobalItems,
	getGlobalItemWithOwnerCount,
	searchGlobalItems,
	upsertGlobalItem,
} 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);
});

// Single item upsert — per D-10
app.post("/", zValidator("json", upsertGlobalItemSchema), async (c) => {
	const db = c.get("db");
	const data = c.req.valid("json");
	const result = await upsertGlobalItem(db, data);
	return c.json(result);
});

// Bulk upsert — per D-06, D-07, D-08
app.post(
	"/bulk",
	zValidator("json", bulkUpsertGlobalItemsSchema),
	async (c) => {
		const db = c.get("db");
		const { items } = c.req.valid("json");
		const result = await bulkUpsertGlobalItems(db, items);
		return c.json(result);
	},
);

export { app as globalItemRoutes };
