import { d as defineEventHandler, c as createError, r as requireAuth, bT as requirePermission, G as createContentManager, j as getQuery, bN as dbQueryOne, E as dbQuery } from '../../../nitro/nitro.mjs';
import { d as deleteMediaById } from '../../../_/media-operations.mjs';
import { f as findMediaUsages } from '../../../_/media-usage.mjs';
import { g as getAuditActorFromEvent } from '../../../_/audit-log-actor.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';
import '../../../_/ids.mjs';
import '../../../_/media-variants.mjs';
import 'sharp';

async function collectDescendantFolderIds(rootId) {
  const allIds = [];
  const queue = [rootId];
  let parentId;
  while ((parentId = queue.shift()) !== void 0) {
    const children = await dbQuery(
      `SELECT id FROM media_folders WHERE parent_id = ?`,
      [parentId]
    );
    for (const child of children) {
      allIds.push(child.id);
      queue.push(child.id);
    }
  }
  return allIds.reverse();
}
async function forceDeleteFolder(rootId, actor) {
  var _a;
  const descendantIds = await collectDescendantFolderIds(rootId);
  const allFolderIds = [...descendantIds, rootId];
  const folderManager = createContentManager("media-folder");
  let deletedFiles = 0;
  const filesByFolder = /* @__PURE__ */ new Map();
  const referencedFiles = [];
  for (const folderId of allFolderIds) {
    const files = await dbQuery(`SELECT id FROM media WHERE folder_id = ?`, [
      folderId
    ]);
    filesByFolder.set(folderId, files);
    for (const file of files) {
      const usages = await findMediaUsages(file.id);
      if (usages.length > 0) {
        referencedFiles.push({ id: file.id, usages });
      }
    }
  }
  if (referencedFiles.length > 0) {
    throw createError({
      statusCode: 409,
      statusMessage: "Conflict",
      message: "Cannot force-delete folder because it contains media used by content. Remove references before deleting it.",
      data: {
        files: referencedFiles,
        total: referencedFiles.reduce((sum, file) => sum + file.usages.length, 0)
      }
    });
  }
  for (const folderId of allFolderIds) {
    const files = (_a = filesByFolder.get(folderId)) != null ? _a : [];
    for (const file of files) {
      await deleteMediaById(file.id, void 0, actor);
      deletedFiles++;
    }
  }
  for (const folderId of allFolderIds) {
    await folderManager.delete(folderId, { actor });
  }
  return { deletedFiles, deletedFolders: allFolderIds.length };
}
const _id__delete = defineEventHandler(async (event) => {
  var _a;
  try {
    const id = parseInt(((_a = event.context.params) == null ? void 0 : _a.id) || "0");
    if (!id || isNaN(id)) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Invalid folder ID"
      });
    }
    await requireAuth(event);
    await requirePermission(
      event.context.user,
      "media",
      "delete",
      event.context.adminUser,
      event.context.apiToken
    );
    const folderManager = createContentManager("media-folder");
    const folder = await folderManager.findOne(id);
    if (!folder) {
      throw createError({
        statusCode: 404,
        statusMessage: "Not Found",
        message: "Folder not found"
      });
    }
    const query = getQuery(event);
    const force = query.force === "true";
    const actor = getAuditActorFromEvent(event);
    if (force) {
      const result = await forceDeleteFolder(id, actor);
      return {
        success: true,
        message: "Folder and all contents deleted",
        data: {
          deletedFiles: result.deletedFiles,
          deletedFolders: result.deletedFolders
        }
      };
    }
    const childResult = await dbQueryOne(
      `SELECT COUNT(*) as count FROM media_folders WHERE parent_id = ?`,
      [id]
    );
    if (Number((childResult == null ? void 0 : childResult.count) || 0) > 0) {
      throw createError({
        statusCode: 409,
        statusMessage: "Conflict",
        message: "Cannot delete folder that contains subfolders. Move or delete them first."
      });
    }
    const fileResult = await dbQueryOne(
      `SELECT COUNT(*) as count FROM media WHERE folder_id = ?`,
      [id]
    );
    if (Number((fileResult == null ? void 0 : fileResult.count) || 0) > 0) {
      throw createError({
        statusCode: 409,
        statusMessage: "Conflict",
        message: "Cannot delete folder that contains files. Move or delete them first."
      });
    }
    await folderManager.delete(id, { actor });
    return {
      success: true,
      message: "Folder deleted"
    };
  } catch (error) {
    const err = error;
    if (err.statusCode) {
      throw error;
    }
    console.error("Delete media folder error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Internal Server Error",
      message: err.message || "Failed to delete media folder"
    });
  }
});

export { _id__delete as default };
//# sourceMappingURL=_id_.delete.mjs.map
