import { env } from "../../../env.js";
import { sessionAuth } from "../../../middleware/sessionAuth.js";
import { OrgRoles, createApiError, waitForPasswordResetLink } from "@inkeep/agents-core";
import { Hono } from "hono";

//#region src/domains/manage/routes/passwordResetLinks.ts
const passwordResetLinksRoutes = new Hono();
passwordResetLinksRoutes.use("*", sessionAuth());
passwordResetLinksRoutes.post("/", async (c) => {
	const tenantId = c.req.param("tenantId");
	const { email } = await c.req.json().catch(() => ({}));
	const userId = c.get("userId");
	if (!tenantId) throw createApiError({
		code: "bad_request",
		message: "Tenant ID is required"
	});
	if (!userId) throw createApiError({
		code: "unauthorized",
		message: "Authentication required"
	});
	if (!email) throw createApiError({
		code: "bad_request",
		message: "Email is required"
	});
	const tenantRole = c.get("tenantRole");
	if (!tenantRole || tenantRole !== OrgRoles.ADMIN && tenantRole !== OrgRoles.OWNER) throw createApiError({
		code: "forbidden",
		message: "Admin access required"
	});
	const auth = c.get("auth");
	if (!auth) throw createApiError({
		code: "internal_server_error",
		message: "Auth not configured"
	});
	if (!(await auth.api.listMembers({
		query: { organizationId: tenantId },
		headers: c.req.raw.headers
	})).members.some((m) => m.user.email === email)) throw createApiError({
		code: "forbidden",
		message: "User is not a member of this organization"
	});
	const redirectTo = `${env.INKEEP_AGENTS_MANAGE_UI_URL || "http://localhost:3000"}/reset-password`;
	const linkPromise = waitForPasswordResetLink(email);
	await auth.api.requestPasswordReset({ body: {
		email,
		redirectTo
	} });
	try {
		const link = await linkPromise;
		return c.json({ url: link.url });
	} catch {
		throw createApiError({
			code: "internal_server_error",
			message: "Reset link not available"
		});
	}
});
var passwordResetLinks_default = passwordResetLinksRoutes;

//#endregion
export { passwordResetLinks_default as default };