import { d as defineEventHandler, c as createError, r as requireAuth, bT as requirePermission, q as readBody, bN as dbQueryOne, G as createContentManager, eC as isUniqueConstraintError } from '../../../nitro/nitro.mjs';
import { a as parsePositiveInt, p as parseNullablePositiveInt } from '../../../_/ids.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';

const _id__put = defineEventHandler(async (event) => {
  var _a, _b;
  try {
    const id = parsePositiveInt((_a = event.context.params) == null ? void 0 : _a.id);
    if (!id) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Invalid folder ID"
      });
    }
    await requireAuth(event);
    await requirePermission(
      event.context.user,
      "media",
      "update",
      event.context.adminUser,
      event.context.apiToken
    );
    const body = await readBody(event);
    const currentFolder = await dbQueryOne(
      `SELECT id, name, parent_id FROM media_folders WHERE id = ?`,
      [id]
    );
    if (!currentFolder) {
      throw createError({
        statusCode: 404,
        statusMessage: "Not Found",
        message: "Folder not found"
      });
    }
    const updateData = {};
    if (body.name !== void 0) {
      if (typeof body.name !== "string" || body.name.trim() === "") {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "Folder name cannot be empty"
        });
      }
      updateData.name = body.name.trim();
    }
    const hasParentChange = "parent" in body;
    let newParentId = currentFolder.parent_id;
    if (hasParentChange) {
      const parsedParentId = parseNullablePositiveInt(body.parent);
      newParentId = parsedParentId.value;
      if (!parsedParentId.valid) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "Invalid parent ID"
        });
      }
      if (newParentId === id) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "A folder cannot be its own parent"
        });
      }
      if (newParentId !== null) {
        const parentExists = await dbQueryOne(`SELECT id FROM media_folders WHERE id = ?`, [
          newParentId
        ]);
        if (!parentExists) {
          throw createError({
            statusCode: 404,
            statusMessage: "Not Found",
            message: "Parent folder not found"
          });
        }
        let checkId = newParentId;
        while (checkId !== null) {
          if (checkId === id) {
            throw createError({
              statusCode: 400,
              statusMessage: "Bad Request",
              message: "Cannot move folder into its own descendant (would create a cycle)"
            });
          }
          const ancestor = await dbQueryOne(`SELECT parent_id FROM media_folders WHERE id = ?`, [checkId]);
          checkId = (_b = ancestor == null ? void 0 : ancestor.parent_id) != null ? _b : null;
        }
      }
      updateData.parent = newParentId;
    }
    if (Object.keys(updateData).length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "No fields to update. Provide name or parent."
      });
    }
    const finalName = updateData.name || currentFolder.name;
    const finalParentId = hasParentChange ? newParentId : currentFolder.parent_id;
    const existingQuery = finalParentId !== null ? `SELECT id FROM media_folders WHERE name = ? AND parent_id = ? AND id != ?` : `SELECT id FROM media_folders WHERE name = ? AND parent_id IS NULL AND id != ?`;
    const existingParams = finalParentId !== null ? [finalName, finalParentId, id] : [finalName, id];
    const existing = await dbQueryOne(existingQuery, existingParams);
    if (existing) {
      throw createError({
        statusCode: 409,
        statusMessage: "Conflict",
        message: `Folder "${finalName}" already exists in the target location`
      });
    }
    const folderManager = createContentManager("media-folder");
    const updated = await folderManager.update(id, updateData, void 0, {
      actor: getAuditActorFromEvent(event)
    });
    return {
      success: true,
      data: updated
    };
  } catch (error) {
    const err = error;
    if (err.statusCode) {
      throw error;
    }
    if (isUniqueConstraintError(error)) {
      throw createError({
        statusCode: 409,
        statusMessage: "Conflict",
        message: "A folder with this name already exists in the target location"
      });
    }
    console.error("Update media folder error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Internal Server Error",
      message: err.message || "Failed to update media folder"
    });
  }
});

export { _id__put as default };
//# sourceMappingURL=_id_.put.mjs.map
