import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { submitCommunityPriceSchema } from "../../shared/schemas.ts";
import {
	getCommunityPriceStats,
	submitCommunityPrice,
} from "../services/community-price.service.ts";

const app = new Hono();

// GET /:globalItemId — returns community price stats for a catalog item (public)
app.get("/:globalItemId", async (c) => {
	const db = c.get("db");
	const globalItemId = Number(c.req.param("globalItemId"));
	if (Number.isNaN(globalItemId))
		return c.json({ error: "Invalid ID" }, 400);

	const market = c.req.query("market");
	const stats = await getCommunityPriceStats(db, globalItemId, market);
	return c.json(stats);
});

// POST / — submit a community price (authenticated, ownership validated)
app.post("/", zValidator("json", submitCommunityPriceSchema), async (c) => {
	const db = c.get("db");
	const userId = c.get("userId");
	if (!userId) return c.json({ error: "Unauthorized" }, 401);

	const data = c.req.valid("json");
	const result = await submitCommunityPrice(db, {
		...data,
		userId,
	});

	if (!result) {
		return c.json(
			{
				error:
					"You must own an item linked to this catalog entry to submit a price",
			},
			403,
		);
	}

	return c.json(result);
});

export { app as communityPriceRoutes };
