import runDbClient_default from "../../../data/db/runDbClient.js";
import { sessionAuth } from "../../../middleware/sessionAuth.js";
import { OrgRoles, createApiError, getUserOrganizationsFromDb, getUserProvidersFromDb } from "@inkeep/agents-core";
import { Hono } from "hono";

//#region src/domains/manage/routes/users.ts
const usersRoutes = new Hono();
usersRoutes.use("*", sessionAuth());
/**
* GET /api/users/:userId/organizations
*
* List all organizations for a user.
* Only allows querying own organizations.
*/
usersRoutes.get("/:userId/organizations", async (c) => {
	const userId = c.req.param("userId");
	const authenticatedUserId = c.get("userId");
	if (!userId) throw createApiError({
		code: "bad_request",
		message: "User ID is required"
	});
	if (userId !== authenticatedUserId) throw createApiError({
		code: "forbidden",
		message: "Cannot access another user's organizations"
	});
	const userOrganizations = (await getUserOrganizationsFromDb(runDbClient_default)(userId)).map((org) => ({
		...org,
		createdAt: org.createdAt.toISOString()
	}));
	return c.json(userOrganizations);
});
/**
* POST /api/users/providers
*
* Get authentication providers for a list of users.
* Returns which providers each user has (e.g., 'credential', 'google', 'auth0').
* Restricted to org admins/owners querying members of their organization.
*
* Body: { userIds: string[], organizationId: string }
* Response: UserProviderInfo[]
*/
usersRoutes.post("/providers", async (c) => {
	const { userIds, organizationId } = await c.req.json();
	const authenticatedUserId = c.get("userId");
	if (!organizationId) throw createApiError({
		code: "bad_request",
		message: "organizationId is required"
	});
	if (!userIds || !Array.isArray(userIds)) throw createApiError({
		code: "bad_request",
		message: "userIds array is required"
	});
	if (userIds.length === 0) return c.json([]);
	const orgAccess = (await getUserOrganizationsFromDb(runDbClient_default)(authenticatedUserId)).find((org) => org.organizationId === organizationId);
	if (!orgAccess) throw createApiError({
		code: "forbidden",
		message: "Access denied to this organization"
	});
	const role = orgAccess.role;
	if (role !== OrgRoles.ADMIN && role !== OrgRoles.OWNER) throw createApiError({
		code: "forbidden",
		message: "Admin access required"
	});
	try {
		const providers = await getUserProvidersFromDb(runDbClient_default)(userIds);
		return c.json(providers);
	} catch (error) {
		console.error("[users/providers] Error fetching providers:", error);
		throw createApiError({
			code: "internal_server_error",
			message: "Failed to fetch user providers"
		});
	}
});
var users_default = usersRoutes;

//#endregion
export { users_default as default };