import { env } from "../env.js";
import { getLogger } from "../logger.js";
import { startSchedulerWorkflow } from "../domains/run/services/SchedulerService.js";
import { OpenAPIHono } from "@hono/zod-openapi";
import { createProtectedRoute, noAuth } from "@inkeep/agents-core/middleware";
import { createHash, timingSafeEqual } from "node:crypto";

//#region src/routes/restartScheduler.ts
const logger = getLogger("deploy-restart-scheduler");
function constantTimeEqual(a, b) {
	const hash = (s) => createHash("sha256").update(s).digest();
	return timingSafeEqual(hash(a), hash(b));
}
const restartWorkflowHandler = new OpenAPIHono();
restartWorkflowHandler.openapi(createProtectedRoute({
	method: "post",
	path: "/api/deploy/restart-scheduler",
	tags: ["Workflows"],
	summary: "Restart scheduler workflow on new deployment",
	description: "Called by CI after deploy to restart the scheduler workflow on the latest deployment. Auth via INKEEP_AGENTS_RUN_API_BYPASS_SECRET.",
	permission: noAuth(),
	responses: {
		200: { description: "Scheduler workflow restarted" },
		401: { description: "Unauthorized" },
		503: { description: "Endpoint not available" }
	}
}), async (c) => {
	if (!env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET) return c.json({ error: "Endpoint not available" }, 503);
	const authHeader = c.req.header("Authorization");
	if (!authHeader?.startsWith("Bearer ")) return c.json({ error: "Unauthorized" }, 401);
	if (!constantTimeEqual(authHeader.slice(7), env.INKEEP_AGENTS_RUN_API_BYPASS_SECRET)) return c.json({ error: "Unauthorized" }, 401);
	try {
		const result = await startSchedulerWorkflow();
		logger.info(result, "Scheduler workflow restarted via deploy hook");
		return c.json(result);
	} catch (err) {
		logger.error({ error: err instanceof Error ? err.message : String(err) }, "Failed to restart scheduler workflow");
		return c.json({ error: "Failed to restart scheduler workflow" }, 500);
	}
});

//#endregion
export { restartWorkflowHandler };