import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import { upsertMarketPriceSchema } from "../../shared/schemas.ts";
import {
	getMarketPrices,
	upsertMarketPrice,
} from "../services/market-price.service.ts";

const app = new Hono();

// GET /global-items/:id/prices — returns market prices for a catalog item (public)
app.get("/global-items/:id/prices", async (c) => {
	const db = c.get("db");
	const id = Number(c.req.param("id"));
	if (Number.isNaN(id)) return c.json({ error: "Invalid ID" }, 400);

	const prices = await getMarketPrices(db, id);
	return c.json({ marketPrices: prices });
});

// POST /global-items/:id/prices — create/update a market price (authenticated)
app.post(
	"/global-items/:id/prices",
	zValidator("json", upsertMarketPriceSchema),
	async (c) => {
		const db = c.get("db");
		const globalItemId = Number(c.req.param("id"));
		if (Number.isNaN(globalItemId))
			return c.json({ error: "Invalid ID" }, 400);

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

		if (!result) return c.json({ error: "Global item not found" }, 404);
		return c.json(result);
	},
);

export { app as marketPriceRoutes };
