import { t as validateIdentifier } from "../../../../../validate-VPnKoIzW.mjs";
import "../../../../../base64-CmWvODNW.mjs";
import "../../../../../types-CuW0zWDA.mjs";
import { n as normalizeMediaValue } from "../../../../../normalize-CeglrBT9.mjs";
import { a as markContentMediaUsageCollectionStaleSafely } from "../../../../../content-refresh-CA4uKwzH.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 "../../../../../redirects-DXEXBAII.mjs";
import { _ as wpRewriteUrlsBody } from "../../../../../byline-fields-2Lp5Hbgf.mjs";
import "../../../../../status-CqJQX1QN.mjs";
import "../../../../../api/schemas/index.mjs";
import { n as requirePerm } from "../../../../../authorize-Dz88F_Fw.mjs";
import { buildBaseUrlMap, extractMediaUrl, findMatchingUrl, rewritePortableTextUrls, rewriteStringUrls } from "./rewrite-url-helpers.mjs";
import { sql } from "kysely";

//#region src/astro/routes/api/import/wordpress/rewrite-urls.ts
const prerender = false;
const POST = async ({ request, locals }) => {
	const { emdash, user } = locals;
	if (!emdash?.db) return apiError("NO_DB", "Database not initialized", 500);
	const denied = requirePerm(user, "import:execute");
	if (denied) return denied;
	try {
		const body = await parseBody(request, wpRewriteUrlsBody);
		if (isParseError(body)) return body;
		if (Object.entries(body.urlMap).length === 0) return apiSuccess({
			updated: 0,
			byCollection: {},
			urlsRewritten: 0,
			errors: []
		});
		const getProvider = (id) => emdash.getMediaProvider(id);
		return apiSuccess(await rewriteUrls(emdash.db, body.urlMap, getProvider, body.collections));
	} catch (error) {
		return handleError(error, "Failed to rewrite URLs", "REWRITE_ERROR");
	}
};
async function rewriteUrls(db, urlMap, getProvider, collections, markUsageCollectionStale = markContentMediaUsageCollectionStaleSafely) {
	const { SchemaRegistry } = await import("../../../../../registry-B65mUtPa.mjs").then((n) => n.r);
	const registry = new SchemaRegistry(db);
	const result = {
		updated: 0,
		byCollection: {},
		urlsRewritten: 0,
		errors: []
	};
	const staleMarkedCollections = /* @__PURE__ */ new Set();
	const staleMarkFailedCollections = /* @__PURE__ */ new Set();
	const markCollectionStale = async (collectionSlug) => {
		if (staleMarkedCollections.has(collectionSlug)) return;
		if (await markUsageCollectionStale(db, collectionSlug, "CONTENT_USAGE_STALE")) {
			staleMarkedCollections.add(collectionSlug);
			staleMarkFailedCollections.delete(collectionSlug);
		} else staleMarkFailedCollections.add(collectionSlug);
	};
	const baseMap = buildBaseUrlMap(urlMap);
	const allCollections = await registry.listCollections();
	const targetCollections = collections?.length ? allCollections.filter((c) => collections.includes(c.slug)) : allCollections;
	try {
		for (const collection of targetCollections) {
			const fields = await registry.listFields(collection.id);
			const portableTextFields = fields.filter((f) => f.type === "portableText");
			const stringFields = fields.filter((f) => ["text", "string"].includes(f.type));
			const mediaFields = fields.filter((f) => ["image", "file"].includes(f.type));
			if (portableTextFields.length === 0 && stringFields.length === 0 && mediaFields.length === 0) continue;
			validateIdentifier(collection.slug, "collection slug");
			const tableName = `ec_${collection.slug}`;
			try {
				const rows = await sql`
				SELECT * FROM ${sql.ref(tableName)}
				WHERE deleted_at IS NULL
			`.execute(db);
				for (const row of rows.rows) {
					let rowUpdated = false;
					const updates = {};
					let rowUrlsRewritten = 0;
					for (const field of portableTextFields) {
						const value = row[field.slug];
						if (!value || typeof value !== "string") continue;
						try {
							const blocks = JSON.parse(value);
							if (!Array.isArray(blocks)) continue;
							const rewriteResult = rewritePortableTextUrls(blocks, urlMap, baseMap);
							if (rewriteResult.changed) {
								updates[field.slug] = JSON.stringify(blocks);
								rowUpdated = true;
								rowUrlsRewritten += rewriteResult.urlsRewritten;
							}
						} catch {
							const stringResult = rewriteStringUrls(value, urlMap, baseMap);
							if (stringResult.changed) {
								updates[field.slug] = stringResult.newValue;
								rowUpdated = true;
								rowUrlsRewritten += stringResult.urlsRewritten;
							}
						}
					}
					for (const field of stringFields) {
						const value = row[field.slug];
						if (!value || typeof value !== "string") continue;
						const stringResult = rewriteStringUrls(value, urlMap, baseMap);
						if (stringResult.changed) {
							updates[field.slug] = stringResult.newValue;
							rowUpdated = true;
							rowUrlsRewritten += stringResult.urlsRewritten;
						}
					}
					for (const field of mediaFields) {
						const value = row[field.slug];
						if (!value || typeof value !== "string") continue;
						const newUrl = findMatchingUrl(extractMediaUrl(value), urlMap, baseMap);
						if (newUrl) {
							try {
								const normalized = await normalizeMediaValue(newUrl, getProvider);
								updates[field.slug] = normalized ? JSON.stringify(normalized) : newUrl;
							} catch {
								updates[field.slug] = newUrl;
							}
							rowUpdated = true;
							rowUrlsRewritten++;
						}
					}
					if (rowUpdated) try {
						let query = db.updateTable(tableName).where("id", "=", row.id);
						for (const [key, value] of Object.entries(updates)) query = query.set({ [key]: value });
						await query.execute();
						result.updated++;
						result.urlsRewritten += rowUrlsRewritten;
						result.byCollection[collection.slug] = (result.byCollection[collection.slug] || 0) + 1;
						await markCollectionStale(collection.slug);
					} catch (updateError) {
						result.errors.push({
							collection: collection.slug,
							id: row.id,
							error: updateError instanceof Error ? updateError.message : "Update failed"
						});
					}
				}
			} catch (queryError) {
				result.errors.push({
					collection: collection.slug,
					id: "*",
					error: queryError instanceof Error ? queryError.message : "Query failed for collection"
				});
			}
		}
	} finally {
		for (const collectionSlug of staleMarkFailedCollections) {
			if (staleMarkedCollections.has(collectionSlug)) continue;
			if (await markUsageCollectionStale(db, collectionSlug, "CONTENT_USAGE_STALE")) staleMarkedCollections.add(collectionSlug);
		}
	}
	return result;
}

//#endregion
export { POST, prerender, rewriteUrls };
//# sourceMappingURL=rewrite-urls.mjs.map