import { d as defineEventHandler, c as createError, G as createContentManager, bo as getStorageProvider, j as getQuery, aP as sendRedirect, g as getHeader, eD as setHeaders, eE as send } from '../../../../nitro/nitro.mjs';
import { a as isProcessableImage, b as getOrCreateTransform, p as parseFocalPoint } from '../../../../_/media-variants.mjs';
import { createHash } from 'crypto';
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 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';
import 'sharp';

const VALID_FITS = /* @__PURE__ */ new Set(["cover", "contain", "fill", "inside", "outside"]);
const VALID_FORMATS = /* @__PURE__ */ new Set(["jpeg", "png", "webp", "avif", "original"]);
const CACHE_MAX_AGE = 31536e3;
const file_get = defineEventHandler(async (event) => {
  var _a;
  const id = Number((_a = event.context.params) == null ? void 0 : _a.id);
  if (!Number.isFinite(id) || id < 1) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: "Invalid media ID"
    });
  }
  const media = await createContentManager("media").findOne(id);
  if (!media) {
    throw createError({
      statusCode: 404,
      statusMessage: "Not Found",
      message: `Media file with ID ${id} not found`
    });
  }
  const mediaPath = media.path;
  const mediaMimeType = media.mimeType;
  const storage = getStorageProvider();
  const query = getQuery(event);
  const hasTransform = hasRequestedTransform(query);
  if (!hasTransform && storage.supportsSignedUrls() && query.redirect === "true") {
    const signedUrl = await storage.getSignedUrl(mediaPath, { expiresIn: CACHE_MAX_AGE });
    return sendRedirect(event, signedUrl, 302);
  }
  if (!hasTransform || !isProcessableImage(mediaMimeType)) {
    const buffer = await storage.getFile(mediaPath);
    const etag2 = generateEtag(buffer);
    const ifNoneMatch2 = getHeader(event, "if-none-match");
    if (ifNoneMatch2 === etag2) {
      event.node.res.statusCode = 304;
      return "";
    }
    setHeaders(event, {
      "Content-Type": mediaMimeType,
      "Content-Length": String(buffer.length),
      "Cache-Control": `public, max-age=${CACHE_MAX_AGE}, immutable`,
      ETag: etag2,
      "Content-Disposition": `inline; filename="${encodeURIComponent(media.originalName)}"`
    });
    return send(event, buffer);
  }
  const transformOptions = parseTransformQuery(query, media);
  const result = await getOrCreateTransform(id, mediaPath, mediaMimeType, transformOptions);
  if (!result) {
    throw createError({
      statusCode: 422,
      statusMessage: "Unprocessable Entity",
      message: "Could not process image transform"
    });
  }
  const etag = generateEtag(result.buffer);
  const ifNoneMatch = getHeader(event, "if-none-match");
  if (ifNoneMatch === etag) {
    event.node.res.statusCode = 304;
    return "";
  }
  setHeaders(event, {
    "Content-Type": result.mimeType,
    "Content-Length": String(result.size),
    "Cache-Control": `public, max-age=${CACHE_MAX_AGE}, immutable`,
    ETag: etag,
    "X-Image-Width": String(result.width),
    "X-Image-Height": String(result.height)
  });
  return send(event, result.buffer);
});
function hasRequestedTransform(query) {
  return Boolean(query.w || query.h || query.q || query.format && query.format !== "original");
}
function parseTransformQuery(query, media) {
  const options = {};
  if (query.w) {
    const w = Number(query.w);
    if (!Number.isFinite(w) || w < 1 || w > 16384) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: 'Parameter "w" must be a number between 1 and 16384'
      });
    }
    options.width = Math.round(w);
  }
  if (query.h) {
    const h = Number(query.h);
    if (!Number.isFinite(h) || h < 1 || h > 16384) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: 'Parameter "h" must be a number between 1 and 16384'
      });
    }
    options.height = Math.round(h);
  }
  if (query.fit) {
    if (!VALID_FITS.has(query.fit)) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: `Parameter "fit" must be one of: ${[...VALID_FITS].join(", ")}`
      });
    }
    options.fit = query.fit;
  }
  if (query.format && query.format !== "original") {
    if (!VALID_FORMATS.has(query.format)) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: `Parameter "format" must be one of: ${[...VALID_FORMATS].join(", ")}`
      });
    }
    options.format = query.format;
  }
  if (query.q) {
    const q = Number(query.q);
    if (!Number.isFinite(q) || q < 1 || q > 100) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: 'Parameter "q" must be a number between 1 and 100'
      });
    }
    options.quality = Math.round(q);
  }
  if (query.fp === "true") {
    const fp = parseFocalPoint(media.focalPoint);
    if (fp) {
      options.focalPoint = fp;
    }
  }
  return options;
}
function generateEtag(buffer) {
  return `"${createHash("md5").update(buffer).digest("hex")}"`;
}

export { file_get as default };
//# sourceMappingURL=file.get.mjs.map
