import { i as runMigrations } from "../../../../runner-K8XK101B.mjs";
import "../../../../dialect-helpers-DRI5pyY3.mjs";
import "../../../../after-B1IIdH3Y.mjs";
import "../../../../object-cache-Bok5j2ae.mjs";
import "../../../../content-DhgEth4k.mjs";
import "../../../../base64-CmWvODNW.mjs";
import "../../../../types-CuW0zWDA.mjs";
import "../../../../media-BrXIaMFN.mjs";
import "../../../../taxonomy-BxGxZZdu.mjs";
import { t as OptionsRepository } from "../../../../options-DTTML-Tx.mjs";
import "../../../../redirect-IyfNirgS.mjs";
import "../../../../request-cache-KCNHp_RJ.mjs";
import "../../../../byline-registry-BOjqDOim.mjs";
import "../../../../field-defs-cache-WUI88LX5.mjs";
import "../../../../byline-Bm8ZgUP9.mjs";
import "../../../../content-refresh-CA4uKwzH.mjs";
import "../../../../fts-manager-BbFaF_V8.mjs";
import "../../../../registry-B65mUtPa.mjs";
import "../../../../loader-CB6YHeul.mjs";
import "../../../../settings-zhmdKyJQ.mjs";
import "../../../../ssrf-1g7usGBg.mjs";
import { n as apiSuccess, r as handleError, t as apiError } from "../../../../error-CkAseSqZ.mjs";
import "../../../../ssrf-CmuGgCq3.mjs";
import { t as validateSeed } from "../../../../validate-CWSnKVIJ.mjs";
import { t as applySeed } from "../../../../apply-Bu-8nYHL.mjs";
import { t as loadSeed } from "../../../../load-Djn3HWQS.mjs";
import { n as getPublicOrigin } from "../../../../public-url-Danv47cS.mjs";
import "../../../../api-tokens-DsvvCtdh.mjs";
import { n as handleApiTokenCreate, t as deleteApiTokensByName } from "../../../../api-tokens-DvqeZmVq.mjs";
import { t as escapeHtml } from "../../../../escape-DqD0aCKu.mjs";
import { t as isSafeRedirect } from "../../../../redirect-CoW3G-0U.mjs";
import { ulid } from "ulidx";

//#region src/astro/routes/api/setup/dev-bypass.ts
const prerender = false;
const ROLE_ADMIN = 50;
const DEV_USER_EMAIL = "dev@emdash.local";
const DEV_USER_NAME = "Dev Admin";
const DEV_SITE_TITLE = "EmDash Dev Site";
async function handleDevBypass(context) {
	if (!import.meta.env.DEV) return apiError("FORBIDDEN", "Dev bypass is only available in development mode", 403);
	const { locals, url, session } = context;
	const { emdash } = locals;
	if (!emdash?.db) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	try {
		const migrations = await runMigrations(emdash.db);
		console.log("[setup-dev-bypass] Migrations applied:", migrations.applied);
		const contentParam = url.searchParams.get("content");
		const includeContent = contentParam !== "0" && contentParam !== "false";
		const seed = await loadSeed();
		if (validateSeed(seed).valid) {
			const seedResult = await applySeed(emdash.db, seed, {
				includeContent,
				onConflict: "skip",
				storage: emdash.storage ?? void 0
			});
			console.log(`[setup-dev-bypass] Seed applied: ${seedResult.collections.created} collections, ${seedResult.fields.created} fields`);
		}
		const options = new OptionsRepository(emdash.db);
		const existingUser = await emdash.db.selectFrom("users").selectAll().where("email", "=", DEV_USER_EMAIL).executeTakeFirst();
		let user;
		let userCreated = false;
		if (!existingUser) {
			const now = (/* @__PURE__ */ new Date()).toISOString();
			const newUser = {
				id: ulid(),
				email: DEV_USER_EMAIL,
				name: DEV_USER_NAME,
				role: ROLE_ADMIN,
				email_verified: 1,
				created_at: now,
				updated_at: now
			};
			await emdash.db.insertInto("users").values(newUser).execute();
			user = {
				id: newUser.id,
				email: newUser.email,
				name: newUser.name,
				role: newUser.role
			};
			userCreated = true;
			console.log("[setup-dev-bypass] Created dev admin user:", user.email);
		} else user = {
			id: existingUser.id,
			email: existingUser.email,
			name: existingUser.name || DEV_USER_NAME,
			role: existingUser.role
		};
		if (!await options.get("emdash:site_title")) await options.set("emdash:site_title", DEV_SITE_TITLE);
		await options.set("emdash:site_url", getPublicOrigin(url, emdash?.config));
		await options.set("emdash:setup_complete", true);
		if (session) session.set("user", { id: user.id });
		let token;
		if (url.searchParams.has("token")) {
			await deleteApiTokensByName(emdash.db, user.id, "dev-bypass-token");
			const result = await handleApiTokenCreate(emdash.db, user.id, {
				name: "dev-bypass-token",
				scopes: [
					"content:read",
					"content:write",
					"media:read",
					"media:write",
					"schema:read",
					"schema:write",
					"admin"
				]
			});
			if (result.success) token = result.data.token;
		}
		const redirect = url.searchParams.get("redirect");
		if (redirect) {
			if (!isSafeRedirect(redirect)) return apiError("INVALID_REDIRECT", "Redirect must be a local path", 400);
			const html = `<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="refresh" content="0;url=${escapeHtml(redirect)}">
</head>
<body>Redirecting...</body>
</html>`;
			return new Response(html, {
				status: 200,
				headers: { "Content-Type": "text/html" }
			});
		}
		return apiSuccess({
			success: true,
			message: "Dev setup complete",
			migrations: migrations.applied,
			userCreated,
			user: {
				id: user.id,
				email: user.email,
				name: user.name,
				role: user.role
			},
			...token ? { token } : {}
		});
	} catch (error) {
		return handleError(error, "Dev bypass failed", "DEV_BYPASS_ERROR");
	}
}
const GET = handleDevBypass;
const POST = handleDevBypass;

//#endregion
export { GET, POST, prerender };
//# sourceMappingURL=dev-bypass.mjs.map