import "../../../base64-CmWvODNW.mjs";
import "../../../types-CuW0zWDA.mjs";
import { t as MediaRepository } from "../../../media-BrXIaMFN.mjs";
import { n as normalizeMime, t as matchesMimeAllowlist } from "../../../mime-CCEzze7W.mjs";
import { t as enrichImageMetadata } from "../../../enrich-BQ0mxJRs.mjs";
import { t as computeContentHash } from "../../../hash-DrvzIXcz.mjs";
import { a as unwrapResult, n as apiSuccess, r as handleError, t as apiError } from "../../../error-CkAseSqZ.mjs";
import { i as parseQuery, t as isParseError } from "../../../parse-GmjecGct.mjs";
import { Bt as DEFAULT_MAX_UPLOAD_SIZE, Kt as mediaListQuery, Vt as formatFileSize } from "../../../redirects-DXEXBAII.mjs";
import "../../../byline-fields-2Lp5Hbgf.mjs";
import "../../../status-CqJQX1QN.mjs";
import "../../../api/schemas/index.mjs";
import { n as requirePerm } from "../../../authorize-Dz88F_Fw.mjs";
import { n as resolveFieldAllowlist, t as GLOBAL_UPLOAD_ALLOWLIST } from "../../../media-allowlist-CRHEeJ_i.mjs";
import { ulid } from "ulidx";
import * as path from "node:path";

//#region src/astro/routes/api/media.ts
/**
* Media list and upload endpoint
*
* GET /_emdash/api/media - List all media
* POST /_emdash/api/media - Upload new media (via configured storage adapter)
*/
const prerender = false;
/**
* Add URL to media items
* Uses relative URLs to ensure portability across deployments
*/
function addUrlToMedia(item) {
	return {
		...item,
		url: `/_emdash/api/media/file/${item.storageKey}`
	};
}
/**
* List media items
*/
const GET = async ({ request, locals }) => {
	const { emdash, user } = locals;
	const denied = requirePerm(user, "media:read");
	if (denied) return denied;
	if (!emdash?.handleMediaList) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	const query = parseQuery(new URL(request.url), mediaListQuery);
	if (isParseError(query)) return query;
	const result = await emdash.handleMediaList({
		cursor: query.cursor,
		limit: query.limit,
		mimeType: query.mimeType,
		q: query.q
	});
	if (!result.success) return unwrapResult(result);
	return apiSuccess({
		items: result.data.items.map((item) => addUrlToMedia(item)),
		nextCursor: result.data.nextCursor
	});
};
/**
* Upload media file
*
* Uses the configured storage adapter to store the file.
*/
const POST = async ({ request, locals }) => {
	const { emdash, user } = locals;
	const denied = requirePerm(user, "media:upload");
	if (denied) return denied;
	if (!emdash?.handleMediaCreate) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	if (!emdash?.storage) return apiError("NO_STORAGE", "Storage not configured", 500);
	try {
		const rawMax = emdash.config.maxUploadSize ?? DEFAULT_MAX_UPLOAD_SIZE;
		if (!Number.isFinite(rawMax) || rawMax <= 0) return apiError("CONFIGURATION_ERROR", "Invalid maxUploadSize configuration", 500);
		const maxUploadSize = rawMax;
		const contentLength = request.headers.get("Content-Length");
		if (contentLength && parseInt(contentLength, 10) > maxUploadSize) return apiError("PAYLOAD_TOO_LARGE", "Upload too large", 413);
		const formData = await request.formData();
		const fileEntry = formData.get("file");
		const file = fileEntry instanceof File ? fileEntry : null;
		if (!file) return apiError("NO_FILE", "No file provided", 400);
		const fieldIdEntry = formData.get("fieldId");
		const fieldId = typeof fieldIdEntry === "string" && fieldIdEntry.length > 0 ? fieldIdEntry : null;
		const allowlist = (fieldId ? await resolveFieldAllowlist(emdash.db, fieldId) : null) ?? [...GLOBAL_UPLOAD_ALLOWLIST];
		if (!matchesMimeAllowlist(file.type, allowlist)) return apiError("INVALID_TYPE", "File type not allowed", 400);
		if (file.size > maxUploadSize) return apiError("PAYLOAD_TOO_LARGE", `File exceeds maximum size of ${formatFileSize(maxUploadSize)}`, 413);
		const buffer = new Uint8Array(await file.arrayBuffer());
		const contentHash = await computeContentHash(buffer);
		const existing = await new MediaRepository(emdash.db).findByContentHash(contentHash);
		if (existing) return apiSuccess({
			item: addUrlToMedia(existing),
			deduplicated: true
		});
		const storageKey = `${ulid()}${path.extname(file.name) || ""}`;
		await emdash.storage.upload({
			key: storageKey,
			body: buffer,
			contentType: file.type
		});
		const widthEntry = formData.get("width");
		const widthStr = typeof widthEntry === "string" ? widthEntry : null;
		const heightEntry = formData.get("height");
		const heightStr = typeof heightEntry === "string" ? heightEntry : null;
		const width = widthStr ? parseInt(widthStr, 10) : void 0;
		const height = heightStr ? parseInt(heightStr, 10) : void 0;
		const thumbnailEntry = formData.get("thumbnail");
		const thumbnail = thumbnailEntry instanceof File ? thumbnailEntry : null;
		const enriched = await enrichImageMetadata(buffer, file.type, {
			knownDimensions: width != null && height != null ? {
				width,
				height
			} : void 0,
			placeholder: thumbnail ? {
				bytes: new Uint8Array(await thumbnail.arrayBuffer()),
				contentType: thumbnail.type
			} : void 0
		});
		const result = await emdash.handleMediaCreate({
			filename: file.name,
			mimeType: normalizeMime(file.type),
			size: file.size,
			width: width ?? enriched.width,
			height: height ?? enriched.height,
			storageKey,
			contentHash,
			blurhash: enriched.blurhash,
			dominantColor: enriched.dominantColor,
			authorId: user?.id
		});
		if (!result.success) {
			try {
				await emdash.storage.delete(storageKey);
			} catch {}
			return unwrapResult(result);
		}
		return apiSuccess({ item: addUrlToMedia(result.data.item) }, 201);
	} catch (error) {
		return handleError(error, "Upload failed", "UPLOAD_ERROR");
	}
};

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