import "../../../../../dialect-helpers-DRI5pyY3.mjs";
import "../../../../../base64-CmWvODNW.mjs";
import "../../../../../types-CuW0zWDA.mjs";
import "../../../../../request-cache-KCNHp_RJ.mjs";
import "../../../../../loader-CB6YHeul.mjs";
import { n as apiSuccess, r as handleError, t as apiError } from "../../../../../error-CkAseSqZ.mjs";
import { n as parseBody, t as isParseError } from "../../../../../parse-GmjecGct.mjs";
import { m as createWidgetBody } from "../../../../../redirects-DXEXBAII.mjs";
import "../../../../../byline-fields-2Lp5Hbgf.mjs";
import "../../../../../status-CqJQX1QN.mjs";
import "../../../../../api/schemas/index.mjs";
import { i as rowToWidget } from "../../../../../widgets-hWcIicX8.mjs";
import { n as requirePerm } from "../../../../../authorize-Dz88F_Fw.mjs";
import { ulid } from "ulidx";

//#region src/astro/routes/api/widget-areas/[name]/widgets.ts
const prerender = false;
const POST = async ({ params, request, locals }) => {
	const { emdash, user } = locals;
	const db = emdash.db;
	const { name } = params;
	const denied = requirePerm(user, "widgets:manage");
	if (denied) return denied;
	if (!name) return apiError("VALIDATION_ERROR", "name is required", 400);
	try {
		const area = await db.selectFrom("_emdash_widget_areas").select("id").where("name", "=", name).executeTakeFirst();
		if (!area) return apiError("NOT_FOUND", `Widget area "${name}" not found`, 404);
		const body = await parseBody(request, createWidgetBody);
		if (isParseError(body)) return body;
		const sortOrder = ((await db.selectFrom("_emdash_widgets").select(({ fn }) => fn.max("sort_order").as("maxOrder")).where("area_id", "=", area.id).executeTakeFirst())?.maxOrder ?? -1) + 1;
		const id = ulid();
		await db.insertInto("_emdash_widgets").values({
			id,
			area_id: area.id,
			sort_order: sortOrder,
			type: body.type,
			title: body.title ?? null,
			content: body.content ? JSON.stringify(body.content) : null,
			menu_name: body.menuName ?? null,
			component_id: body.componentId ?? null,
			component_props: body.componentProps ? JSON.stringify(body.componentProps) : null
		}).execute();
		return apiSuccess(rowToWidget(await db.selectFrom("_emdash_widgets").selectAll().$castTo().where("id", "=", id).executeTakeFirstOrThrow()), 201);
	} catch (error) {
		return handleError(error, "Failed to create widget", "WIDGET_CREATE_ERROR");
	}
};

//#endregion
export { POST, prerender };
//# sourceMappingURL=widgets.mjs.map