import runDbClient_default from "../../../data/db/runDbClient.js";
import { sessionAuth } from "../../../middleware/sessionAuth.js";
import { createApiError, getPendingInvitationsByEmail } from "@inkeep/agents-core";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";

//#region src/domains/manage/routes/invitations.ts
const invitationsRoutes = new Hono();
/**
* GET /api/invitations/verify?email=user@example.com&id=xxx
*
* Unauthenticated endpoint to validate an invitation exists and get preview info.
* Used by the accept-invitation page to pre-populate signup forms.
*
* Returns limited info: email, organizationName, organizationId, role, expiresAt
*/
invitationsRoutes.get("/verify", async (c) => {
	const email = c.req.query("email");
	const invitationId = c.req.query("id");
	if (!email) throw createApiError({
		code: "bad_request",
		message: "Email parameter is required"
	});
	if (!invitationId) throw createApiError({
		code: "bad_request",
		message: "Invitation ID parameter is required"
	});
	const auth = c.get("auth");
	if (!auth) throw createApiError({
		code: "internal_server_error",
		message: "Auth not configured"
	});
	try {
		const invitations = await auth.api.listUserInvitations({ query: { email } });
		const invitation = Array.isArray(invitations) ? invitations.find((inv) => inv.id === invitationId) : null;
		if (!invitation) throw createApiError({
			code: "not_found",
			message: "Invitation not found"
		});
		const expiresAt = invitation.expiresAt ? new Date(invitation.expiresAt) : null;
		const isExpired = expiresAt && expiresAt < /* @__PURE__ */ new Date();
		if (!(invitation.status === "pending")) throw createApiError({
			code: "not_found",
			message: "Invitation is no longer valid"
		});
		if (isExpired) throw createApiError({
			code: "not_found",
			message: "Invitation has expired"
		});
		return c.json({
			valid: true,
			email: invitation.email,
			organizationName: invitation.organizationName || null,
			organizationId: invitation.organizationId,
			role: invitation.role,
			expiresAt: invitation.expiresAt
		});
	} catch (error) {
		if (error instanceof HTTPException) throw error;
		console.error("[invitations/verify] Error fetching invitation:", error);
		throw createApiError({
			code: "internal_server_error",
			message: "Failed to validate invitation"
		});
	}
});
invitationsRoutes.use("*", sessionAuth());
invitationsRoutes.get("/pending", async (c) => {
	const email = c.req.query("email");
	const authenticatedEmail = c.get("userEmail");
	if (!email) throw createApiError({
		code: "bad_request",
		message: "Email parameter is required"
	});
	if (email !== authenticatedEmail) throw createApiError({
		code: "forbidden",
		message: "Cannot access invitations for another email"
	});
	const response = (await getPendingInvitationsByEmail(runDbClient_default)(email)).map((inv) => ({
		...inv,
		expiresAt: inv.expiresAt instanceof Date ? inv.expiresAt.getTime() : inv.expiresAt
	}));
	return c.json(response);
});
var invitations_default = invitationsRoutes;

//#endregion
export { invitations_default as default };