import { zValidator } from "@hono/zod-validator";
import { Hono } from "hono";
import {
	createCandidateSchema,
	createThreadSchema,
	reorderCandidatesSchema,
	resolveThreadSchema,
	updateCandidateSchema,
	updateThreadSchema,
} from "../../shared/schemas.ts";
import { parseId } from "../lib/params.ts";
import { deleteImage, withImageUrls } from "../services/storage.service.ts";
import {
	createCandidate,
	createThread,
	deleteCandidate,
	deleteThread,
	getAllThreads,
	getThreadWithCandidates,
	reorderCandidates,
	resolveThread,
	updateCandidate,
	updateThread,
} from "../services/thread.service.ts";

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

const app = new Hono<Env>();

// Thread CRUD

app.get("/", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const includeResolved = c.req.query("includeResolved") === "true";
	const threads = await getAllThreads(db, userId, includeResolved);
	return c.json(threads);
});

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

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 thread ID" }, 400);
	const thread = await getThreadWithCandidates(db, userId, id);
	if (!thread) return c.json({ error: "Thread not found" }, 404);
	const enrichedCandidates = await withImageUrls(thread.candidates);
	return c.json({ ...thread, candidates: enrichedCandidates });
});

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

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

	// Clean up candidate images from object storage
	for (const filename of deleted.candidateImages) {
		try {
			await deleteImage(filename);
		} catch {
			// Missing object is not an error worth failing the delete over
		}
	}

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

// Candidate CRUD (nested under thread)

app.post(
	"/:id/candidates",
	zValidator("json", createCandidateSchema),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const threadId = parseId(c.req.param("id"));
		if (!threadId) return c.json({ error: "Invalid thread ID" }, 400);

		// Verify thread exists
		const thread = await getThreadWithCandidates(db, userId, threadId);
		if (!thread) return c.json({ error: "Thread not found" }, 404);

		const data = c.req.valid("json");
		const candidate = await createCandidate(db, userId, threadId, data);
		return c.json(candidate, 201);
	},
);

app.put(
	"/:threadId/candidates/:candidateId",
	zValidator("json", updateCandidateSchema),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const candidateId = parseId(c.req.param("candidateId"));
		if (!candidateId) return c.json({ error: "Invalid candidate ID" }, 400);
		const data = c.req.valid("json");
		const candidate = await updateCandidate(db, userId, candidateId, data);
		if (!candidate) return c.json({ error: "Candidate not found" }, 404);
		return c.json(candidate);
	},
);

app.delete("/:threadId/candidates/:candidateId", async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const candidateId = parseId(c.req.param("candidateId"));
	if (!candidateId) return c.json({ error: "Invalid candidate ID" }, 400);
	const deleted = await deleteCandidate(db, userId, candidateId);
	if (!deleted) return c.json({ error: "Candidate not found" }, 404);

	// Clean up image from object storage if exists
	if (deleted.imageFilename) {
		try {
			await deleteImage(deleted.imageFilename);
		} catch {
			// Missing object is not an error
		}
	}

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

// Candidate reorder

app.patch(
	"/:id/candidates/reorder",
	zValidator("json", reorderCandidatesSchema),
	async (c) => {
		const db = c.get("db");
		const userId = c.get("userId")!;
		const threadId = parseId(c.req.param("id"));
		if (!threadId) return c.json({ error: "Invalid thread ID" }, 400);
		const { orderedIds } = c.req.valid("json");
		const result = await reorderCandidates(db, userId, threadId, orderedIds);
		if (!result.success) return c.json({ error: result.error }, 400);
		return c.json({ success: true });
	},
);

// Resolution

app.post("/:id/resolve", zValidator("json", resolveThreadSchema), async (c) => {
	const db = c.get("db");
	const userId = c.get("userId")!;
	const threadId = parseId(c.req.param("id"));
	if (!threadId) return c.json({ error: "Invalid thread ID" }, 400);
	const { candidateId } = c.req.valid("json");

	const result = await resolveThread(db, userId, threadId, candidateId);
	if (!result.success) {
		return c.json({ error: result.error }, 400);
	}

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

export { app as threadRoutes };
