import { d as defineEventHandler, dL as optionalAuth, bT as requirePermission, E as dbQuery, c as createError } from '../../../nitro/nitro.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';

const tree_get = defineEventHandler(async (event) => {
  try {
    await optionalAuth(event);
    await requirePermission(
      event.context.user,
      "media",
      "read",
      event.context.adminUser,
      event.context.apiToken
    );
    const allFolders = await dbQuery(`SELECT * FROM media_folders ORDER BY name ASC`);
    const fileCounts = await dbQuery(
      `SELECT folder_id, COUNT(*) as count FROM media WHERE folder_id IS NOT NULL GROUP BY folder_id`
    );
    const fileCountMap = new Map(fileCounts.map((r) => [r.folder_id, Number(r.count)]));
    const childCountMap = /* @__PURE__ */ new Map();
    for (const folder of allFolders) {
      if (folder.parent_id !== null) {
        childCountMap.set(folder.parent_id, (childCountMap.get(folder.parent_id) || 0) + 1);
      }
    }
    const buildTree = (parentId) => {
      return allFolders.filter((f) => f.parent_id === parentId).map((f) => ({
        id: f.id,
        name: f.name,
        parent: f.parent_id,
        createdAt: f.created_at,
        updatedAt: f.updated_at,
        childCount: childCountMap.get(f.id) || 0,
        fileCount: fileCountMap.get(f.id) || 0,
        children: buildTree(f.id)
      }));
    };
    const tree = buildTree(null);
    return {
      success: true,
      data: tree
    };
  } catch (error) {
    const err = error;
    if (err.statusCode) {
      throw error;
    }
    console.error("Get media folders tree error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Internal Server Error",
      message: err.message || "Failed to get media folders tree"
    });
  }
});

export { tree_get as default };
//# sourceMappingURL=tree.get.mjs.map
