import { useRuntimeConfig } from "#imports";
const resolveAssetBaseUrl = () => {
  const config = useRuntimeConfig();
  const raw = String(config?.public?.ASSET_URL ?? "/asset/").trim();
  if (raw === "") {
    return "/asset";
  }
  return raw.replace(/\/+$/g, "");
};
const xorObfuscate = (input, key) => {
  if (key.length === 0) {
    return input;
  }
  let output = "";
  for (let i = 0; i < input.length; i++) {
    output += String.fromCharCode(input.charCodeAt(i) ^ key.charCodeAt(i % key.length));
  }
  return output;
};
const toBase64UrlString = (value) => {
  return btoa(value).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
};
const generateRandomKey = (length = 12) => {
  const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  const bytes = new Uint8Array(length);
  if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
    crypto.getRandomValues(bytes);
  } else {
    for (let i = 0; i < length; i++) {
      bytes[i] = Math.floor(Math.random() * 256);
    }
  }
  let key = "";
  for (let i = 0; i < length; i++) {
    key += chars[bytes[i] % chars.length];
  }
  return key;
};
export const encryptAssetToken = (assetId) => {
  const timestamp = Date.now();
  const payload = `${timestamp}|${assetId}`;
  const key = generateRandomKey();
  const encryptedPayload = toBase64UrlString(xorObfuscate(payload, key));
  return toBase64UrlString(`${key}|${encryptedPayload}`);
};
export const assetUrl = (assetId) => {
  const token = encryptAssetToken(assetId);
  return `${resolveAssetBaseUrl()}/${token}`;
};
