import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
	createCategorySchema,
	updateCategorySchema,
} from "../../shared/schemas.ts";
import { parseId } from "../lib/params.ts";
import {
	createCategory,
	deleteCategory,
	getAllCategories,
	updateCategory,
} from "../services/category.service.ts";

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

const app = new Hono<Env>();

app.get("/", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const cats = await getAllCategories(db, userId);
	return c.json(cats);
});

app.post("/", zValidator("json", createCategorySchema), async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const data = c.req.valid("json");
	const cat = await createCategory(db, userId, data);
	return c.json(cat, 201);
});

app.put(
	"/:id",
	zValidator("json", updateCategorySchema.omit({ id: true })),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const id = parseId(c.req.param("id"));
		if (!id) return c.json({ error: "Invalid category ID" }, 400);
		const data = c.req.valid("json");
		const cat = await updateCategory(db, userId, id, data);
		if (!cat) return c.json({ error: "Category not found" }, 404);
		return c.json(cat);
	},
);

app.delete("/:id", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const id = parseId(c.req.param("id"));
	if (!id) return c.json({ error: "Invalid category ID" }, 400);
	const result = await deleteCategory(db, userId, id);

	if (!result.success) {
		if (result.error === "Cannot delete the Uncategorized category") {
			return c.json({ error: result.error }, 400);
		}
		return c.json({ error: result.error }, 404);
	}

	return c.json({ success: true });
});

export { app as categoryRoutes };
