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 { p as createWidgetAreaBody } 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/index.ts
const prerender = false;
const GET = async ({ locals }) => {
	const { emdash, user } = locals;
	const db = emdash.db;
	const denied = requirePerm(user, "widgets:read");
	if (denied) return denied;
	try {
		const areas = await db.selectFrom("_emdash_widget_areas").selectAll().orderBy("name", "asc").execute();
		return apiSuccess({ items: await Promise.all(areas.map(async (area) => {
			const widgets = await db.selectFrom("_emdash_widgets").selectAll().$castTo().where("area_id", "=", area.id).orderBy("sort_order", "asc").execute();
			return {
				...area,
				widgets: widgets.map((row) => rowToWidget(row)),
				widgetCount: widgets.length
			};
		})) });
	} catch (error) {
		return handleError(error, "Failed to fetch widget areas", "WIDGET_AREA_LIST_ERROR");
	}
};
const POST = async ({ request, locals }) => {
	const { emdash, user } = locals;
	const db = emdash.db;
	const denied = requirePerm(user, "widgets:manage");
	if (denied) return denied;
	try {
		const body = await parseBody(request, createWidgetAreaBody);
		if (isParseError(body)) return body;
		if (await db.selectFrom("_emdash_widget_areas").select("id").where("name", "=", body.name).executeTakeFirst()) return apiError("CONFLICT", `Widget area with name "${body.name}" already exists`, 409);
		const id = ulid();
		await db.insertInto("_emdash_widget_areas").values({
			id,
			name: body.name,
			label: body.label,
			description: body.description ?? null
		}).execute();
		return apiSuccess(await db.selectFrom("_emdash_widget_areas").selectAll().where("id", "=", id).executeTakeFirstOrThrow(), 201);
	} catch (error) {
		return handleError(error, "Failed to create widget area", "WIDGET_AREA_CREATE_ERROR");
	}
};

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