import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
	createSetupSchema,
	createShareLinkSchema,
	syncSetupItemsSchema,
	updateClassificationSchema,
	updateSetupSchema,
} from "../../shared/schemas.ts";
import { parseId } from "../lib/params.ts";
import { getPublicSetupWithItems } from "../services/profile.service.ts";
import {
	createSetup,
	deleteSetup,
	getAllSetups,
	getSetupWithItems,
	removeSetupItem,
	syncSetupItems,
	updateItemClassification,
	updateSetup,
} from "../services/setup.service.ts";
import {
	createShareLink,
	getShareLinks,
	revokeShareLink,
} from "../services/share.service.ts";
import { withImageUrls } from "../services/storage.service.ts";

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

const app = new Hono<Env>();

// Setup CRUD

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

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

// Public setup view (no auth required — skipped in index.ts middleware)
app.get("/:id/public", async (c) => {
	const db = c.get("db");
	const id = parseId(c.req.param("id"));
	if (!id) return c.json({ error: "Invalid setup ID" }, 400);
	const setup = await getPublicSetupWithItems(db, id);
	if (!setup) return c.json({ error: "Setup not found" }, 404);
	const enrichedItems = await withImageUrls(setup.items);
	return c.json({ ...setup, items: enrichedItems });
});

app.get("/: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 setup ID" }, 400);
	const setup = await getSetupWithItems(db, userId, id);
	if (!setup) return c.json({ error: "Setup not found" }, 404);
	const enrichedItems = await withImageUrls(setup.items);
	return c.json({ ...setup, items: enrichedItems });
});

app.put("/:id", zValidator("json", updateSetupSchema), 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 setup ID" }, 400);
	const data = c.req.valid("json");
	const setup = await updateSetup(db, userId, id, data);
	if (!setup) return c.json({ error: "Setup not found" }, 404);
	return c.json(setup);
});

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 setup ID" }, 400);
	const deleted = await deleteSetup(db, userId, id);
	if (!deleted) return c.json({ error: "Setup not found" }, 404);
	return c.json({ success: true });
});

// Setup Items

app.put("/:id/items", zValidator("json", syncSetupItemsSchema), 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 setup ID" }, 400);
	const { itemIds } = c.req.valid("json");

	const setup = await getSetupWithItems(db, userId, id);
	if (!setup) return c.json({ error: "Setup not found" }, 404);

	await syncSetupItems(db, userId, id, itemIds);
	return c.json({ success: true });
});

app.patch(
	"/:id/items/:itemId/classification",
	zValidator("json", updateClassificationSchema),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const setupId = parseId(c.req.param("id"));
		const itemId = parseId(c.req.param("itemId"));
		if (!setupId || !itemId) return c.json({ error: "Invalid ID" }, 400);
		const { classification } = c.req.valid("json");
		await updateItemClassification(db, userId, setupId, itemId, classification);
		return c.json({ success: true });
	},
);

app.delete("/:id/items/:itemId", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const setupId = parseId(c.req.param("id"));
	const itemId = parseId(c.req.param("itemId"));
	if (!setupId || !itemId) return c.json({ error: "Invalid ID" }, 400);
	await removeSetupItem(db, userId, setupId, itemId);
	return c.json({ success: true });
});

// Share Links

app.post(
	"/:id/shares",
	zValidator("json", createShareLinkSchema),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const setupId = parseId(c.req.param("id"));
		if (!setupId) return c.json({ error: "Invalid setup ID" }, 400);
		const data = c.req.valid("json");
		const share = await createShareLink(db, userId, setupId, {
			expiresInDays: data.expiresInDays,
		});
		if (!share) return c.json({ error: "Setup not found" }, 404);
		return c.json(share, 201);
	},
);

app.get("/:id/shares", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const setupId = parseId(c.req.param("id"));
	if (!setupId) return c.json({ error: "Invalid setup ID" }, 400);
	const links = await getShareLinks(db, userId, setupId);
	if (!links) return c.json({ error: "Setup not found" }, 404);
	return c.json(links);
});

app.delete("/:id/shares/:shareId", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const shareId = parseId(c.req.param("shareId"));
	if (!shareId) return c.json({ error: "Invalid share ID" }, 400);
	const share = await revokeShareLink(db, userId, shareId);
	if (!share) return c.json({ error: "Share not found" }, 404);
	return c.json(share);
});

export { app as setupRoutes };
