import { d as defineEventHandler, c as createError, r as requireAuth, bT as requirePermission, eF as readMultipartFormData, as as config, bo as getStorageProvider, G as createContentManager, dM as emitMediaUpdate } from '../../../../nitro/nitro.mjs';
import { a as parsePositiveInt } from '../../../../_/ids.mjs';
import { g as getMediaEntryOrThrow } from '../../../../_/media-operations.mjs';
import { a as isProcessableImage, n as normalizeImage, p as parseFocalPoint, c as getImageMetadata, g as generateMediaVariants, d as deleteMediaVariants, i as invalidateTransformCache } from '../../../../_/media-variants.mjs';
import { e as enrichMediaDeliveryRecord } from '../../../../_/media-delivery.mjs';
import { g as getAuditActorFromEvent } from '../../../../_/audit-log-actor.mjs';
import { d as detectUploadMimeType, a as assertUploadFileAccepted } from '../../../../_/media-upload-validation.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 '../../../../_/media-usage.mjs';
import 'sharp';

const file_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 media ID"
      });
    }
    await requireAuth(event);
    await requirePermission(
      event.context.user,
      "media",
      "update",
      event.context.adminUser,
      event.context.apiToken
    );
    const existing = await getMediaEntryOrThrow(id);
    const formData = await readMultipartFormData(event);
    if (!formData || formData.length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "No file provided"
      });
    }
    const filePart = formData.find((part) => part.filename && part.data);
    if (!filePart || !filePart.filename || !filePart.data) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "No valid file found in request"
      });
    }
    const filename = filePart.filename;
    const mimeType = detectUploadMimeType(filename);
    const maxUploadSize = config.get("media.maxUploadSize", 10 * 1024 * 1024);
    const allowedFileTypes = config.get("media.allowedMimeTypes", []);
    assertUploadFileAccepted({
      allowedMimeTypes: allowedFileTypes,
      filename,
      maxUploadSize,
      mimeType,
      size: filePart.data.length
    });
    const storage = getStorageProvider();
    const mediaManager = createContentManager("media");
    const actor = getAuditActorFromEvent(event);
    const oldPath = typeof existing.path === "string" ? existing.path : "";
    const oldFormats = parseFormatsField(existing.formats);
    let fileBuffer = filePart.data;
    if (isProcessableImage(mimeType)) {
      try {
        fileBuffer = await normalizeImage(filePart.data);
      } catch {
        fileBuffer = filePart.data;
      }
    }
    const uploadedFile = await storage.upload(fileBuffer, {
      filename,
      mimeType,
      allowedMimeTypes: allowedFileTypes,
      maxSize: maxUploadSize
    });
    const updateData = {
      filename: uploadedFile.filename,
      originalName: uploadedFile.originalName,
      mimeType,
      size: uploadedFile.size,
      path: uploadedFile.path,
      url: uploadedFile.url,
      storageProvider: storage.getType(),
      width: null,
      height: null,
      formats: null,
      focalPoint: null
    };
    const retainedFocalPoint = isProcessableImage(mimeType) ? (_b = parseFocalPoint(existing.focalPoint)) != null ? _b : null : null;
    updateData.focalPoint = retainedFocalPoint;
    if (isProcessableImage(mimeType)) {
      try {
        const imageMeta = await getImageMetadata(fileBuffer);
        updateData.width = imageMeta.width;
        updateData.height = imageMeta.height;
      } catch {
      }
    }
    let nextFormats = null;
    try {
      nextFormats = await generateMediaVariants(fileBuffer, uploadedFile.path, mimeType, {
        focalPoint: retainedFocalPoint,
        variantSuffix: `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
      });
      if (nextFormats) {
        updateData.formats = nextFormats;
      }
    } catch {
    }
    let updated;
    try {
      updated = await mediaManager.update(id, updateData, void 0, { actor });
    } catch (error) {
      await storage.delete({ path: uploadedFile.path }).catch(() => {
      });
      await deleteMediaVariants(nextFormats).catch(() => {
      });
      throw error;
    }
    const enriched = await enrichMediaDeliveryRecord(updated);
    if (enriched.url !== updated.url) {
      await mediaManager.update(id, { url: enriched.url }, void 0, { actor }).catch(() => {
      });
    }
    if (oldPath && oldPath !== uploadedFile.path) {
      await storage.delete({ path: oldPath }).catch(() => {
      });
    }
    await deleteMediaVariants(oldFormats).catch(() => {
    });
    await invalidateTransformCache(id).catch(() => {
    });
    await emitMediaUpdate(id, enriched, actor);
    return {
      success: true,
      data: enriched
    };
  } catch (error) {
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    console.error("Replace media file error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Internal Server Error",
      message: error instanceof Error ? error.message : "Failed to replace media file"
    });
  }
});
function parseFormatsField(value) {
  if (!value) {
    return null;
  }
  if (typeof value === "string") {
    try {
      return JSON.parse(value);
    } catch {
      return null;
    }
  }
  if (typeof value === "object" && !Array.isArray(value)) {
    const obj = value;
    if (obj.variants && typeof obj.variants === "object") {
      return value;
    }
  }
  return null;
}

export { file_put as default };
//# sourceMappingURL=file.put.mjs.map
