import { d as defineEventHandler, dL as optionalAuth, bT as requirePermission, j as getQuery, c as createError, bO as buildMediaSearchClause, bN as dbQueryOne, E as dbQuery } from '../../nitro/nitro.mjs';
import { a as resolveMediaUrl } from '../../_/media-delivery.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 HEAVY_ASSET_BYTES = 15e5;
const SORT_COLUMNS = {
  id: "id",
  created_at: "created_at",
  updated_at: "updated_at",
  filename: "filename",
  originalname: "originalName",
  originalName: "originalName",
  size: "size",
  mimetype: "mimeType",
  mimeType: "mimeType",
  storageprovider: "storageProvider",
  storageProvider: "storageProvider"
};
function parsePositiveInt(value, fallback) {
  if (!value) {
    return fallback;
  }
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed <= 0) {
    return fallback;
  }
  return parsed;
}
function parseNonNegativeInt(value, fallback) {
  if (!value) {
    return fallback;
  }
  const parsed = Number.parseInt(value, 10);
  if (!Number.isFinite(parsed) || parsed < 0) {
    return fallback;
  }
  return parsed;
}
function normalizeTimestamp(value) {
  if (value instanceof Date) {
    return value.toISOString();
  }
  if (typeof value !== "string") {
    return "";
  }
  if (/[Z+\-]\d{0,4}$/.test(value)) {
    return value;
  }
  if (/^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}:\d{2}/.test(value)) {
    return value.replace(" ", "T") + "Z";
  }
  return value;
}
function toOptionalNumber(value) {
  if (value === null || value === void 0 || value === "") {
    return void 0;
  }
  const parsed = Number(value);
  return Number.isFinite(parsed) ? parsed : void 0;
}
function mapMediaRow(row) {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
  const folderId = (_c = (_b = (_a = row.folder_id) != null ? _a : row.folderId) != null ? _b : row.folder) != null ? _c : null;
  const id = Number(row.id);
  const storageProvider = String((_e = (_d = row.storageProvider) != null ? _d : row.storageprovider) != null ? _e : "local");
  return {
    id,
    filename: String((_f = row.filename) != null ? _f : ""),
    originalName: String((_h = (_g = row.originalName) != null ? _g : row.originalname) != null ? _h : ""),
    mimeType: String((_j = (_i = row.mimeType) != null ? _i : row.mimetype) != null ? _j : ""),
    size: Number((_k = row.size) != null ? _k : 0),
    path: String((_l = row.path) != null ? _l : ""),
    url: resolveMediaUrl(id, storageProvider, row.url),
    folder: folderId === null ? null : Number(folderId),
    alt: typeof row.alt === "string" ? row.alt : void 0,
    caption: typeof row.caption === "string" ? row.caption : void 0,
    width: toOptionalNumber(row.width),
    height: toOptionalNumber(row.height),
    storageProvider,
    created_at: normalizeTimestamp(row.created_at),
    updated_at: normalizeTimestamp(row.updated_at)
  };
}
function applyTypeFilter(clauses, params, typeFilter) {
  switch (typeFilter) {
    case void 0:
      return;
    case "images":
      clauses.push("mimeType LIKE ?");
      params.push("image/%");
      return;
    case "videos":
      clauses.push("mimeType LIKE ?");
      params.push("video/%");
      return;
    case "audio":
      clauses.push("mimeType LIKE ?");
      params.push("audio/%");
      return;
    case "files":
    case "documents":
      clauses.push(
        "(mimeType IS NULL OR (mimeType NOT LIKE ? AND mimeType NOT LIKE ? AND mimeType NOT LIKE ?))"
      );
      params.push("image/%", "video/%", "audio/%");
      return;
    default:
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: `Unsupported media type filter: ${typeFilter}`
      });
  }
}
const index_get = defineEventHandler(async (event) => {
  var _a, _b, _c;
  try {
    await optionalAuth(event);
    await requirePermission(
      event.context.user,
      "media",
      "read",
      event.context.adminUser,
      event.context.apiToken
    );
    const query = getQuery(event);
    const limit = Math.min(parsePositiveInt(query.limit, 25), 200);
    const offset = parseNonNegativeInt(query.offset, 0);
    const sortKey = (_a = query.sort) != null ? _a : "id";
    const sortColumn = (_b = SORT_COLUMNS[sortKey]) != null ? _b : SORT_COLUMNS.id;
    const sortOrder = ((_c = query.sortOrder) == null ? void 0 : _c.toLowerCase()) === "asc" ? "ASC" : "DESC";
    const clauses = [];
    const params = [];
    const folderParam = query.folder;
    if (folderParam === "root") {
      clauses.push("folder_id IS NULL");
    } else if (folderParam !== void 0) {
      const folderId = parsePositiveInt(folderParam, -1);
      if (folderId <= 0) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "Invalid folder ID"
        });
      }
      clauses.push("folder_id = ?");
      params.push(folderId);
    }
    if (typeof query.mimeType === "string" && query.mimeType.trim()) {
      clauses.push("mimeType = ?");
      params.push(query.mimeType.trim());
    }
    if (typeof query.storageProvider === "string" && query.storageProvider.trim()) {
      clauses.push("storageProvider = ?");
      params.push(query.storageProvider.trim());
    }
    if (query.missingAlt === "true") {
      clauses.push("(alt IS NULL OR alt = '') AND mimeType LIKE ?");
      params.push("image/%");
    }
    if (query.heavy === "true") {
      clauses.push("size > ?");
      params.push(HEAVY_ASSET_BYTES);
    }
    applyTypeFilter(clauses, params, query.type);
    const searchTerm = typeof query.search === "string" ? query.search.trim() : "";
    if (searchTerm) {
      const { getSearchService } = await import('../../_/index.mjs');
      const searchService = getSearchService();
      const adapter = searchService.getAdapter();
      if (adapter.capabilities.externalIndex) {
        const searchResult = await searchService.search("media", {
          query: searchTerm,
          limit: limit + offset,
          offset: 0
        });
        const matchedIds = searchResult.hits.map(
          (h) => {
            var _a2;
            return Number((_a2 = h.document.id) != null ? _a2 : h.document.id);
          }
        );
        if (matchedIds.length === 0) {
          return {
            success: true,
            data: [],
            pagination: { total: 0, limit, offset, hasMore: false }
          };
        }
        clauses.push(`id IN (${matchedIds.map(() => "?").join(",")})`);
        params.push(...matchedIds);
      } else {
        const mediaSearch = buildMediaSearchClause(searchTerm);
        clauses.push(mediaSearch.clause);
        params.push(...mediaSearch.params);
      }
    }
    const whereClause = clauses.length > 0 ? `WHERE ${clauses.join(" AND ")}` : "";
    const countResult = await dbQueryOne(
      `SELECT COUNT(*) as count FROM media ${whereClause}`,
      params
    );
    const total = countResult ? Number(countResult.count) : 0;
    const rows = await dbQuery(
      `SELECT * FROM media ${whereClause} ORDER BY ${sortColumn} ${sortOrder} LIMIT ? OFFSET ?`,
      [...params, limit, offset]
    );
    const data = rows.map(mapMediaRow);
    return {
      success: true,
      data,
      pagination: {
        total,
        limit,
        offset,
        hasMore: offset + data.length < total
      }
    };
  } catch (error) {
    console.error("Get media list error:", error);
    const err = error;
    throw createError({
      statusCode: err.statusCode || 500,
      statusMessage: err.statusMessage || "Internal Server Error",
      message: err.message || "Failed to get media list"
    });
  }
});

export { index_get as default };
//# sourceMappingURL=index.get3.mjs.map
