const { getRedisClient } = require("./client")

const BARCODE_KEY_PREFIX = "linkpreview:barcode:"
const DEFAULT_TTL_SECONDS = 15 * 60

function createRedisClient() {
  return getRedisClient()
}

function normalizeUrl(rawUrl) {
  if (!rawUrl || typeof rawUrl !== "string") return null
  try {
    const url = new URL(rawUrl)
    const hostname = url.hostname.toLowerCase()
    const pathname = url.pathname || "/"
    return `${url.protocol}//${hostname}${pathname}`
  } catch {
    return null
  }
}

async function setBarcodeForUrl(url, barcodeId, { ttlSeconds = DEFAULT_TTL_SECONDS } = {}) {
  const normalized = normalizeUrl(url)
  if (!normalized) return { saved: false }
  if (barcodeId === undefined || barcodeId === null || barcodeId === "") return { saved: false }

  const redis = createRedisClient()
  const key = `${BARCODE_KEY_PREFIX}${normalized}`
  try {
    await redis.set(key, String(barcodeId), "EX", Number(ttlSeconds) || DEFAULT_TTL_SECONDS)
    return { saved: true }
  } catch {
    return { saved: false }
  } finally {}
}

async function getBarcodeForUrl(url) {
  const normalized = normalizeUrl(url)
  if (!normalized) return null
  const redis = createRedisClient()
  const key = `${BARCODE_KEY_PREFIX}${normalized}`
  try {
    const raw = await redis.get(key)
    return raw ?? null
  } catch {
    return null
  } finally {}
}

module.exports = {
  setBarcodeForUrl,
  getBarcodeForUrl,
}
