// Media storage: local disk (public/media) or Vercel Blob.
//
// The site always refers to media as `/media/<path>` (content JSON, product images, uploads).
// - Without BLOB_READ_WRITE_TOKEN: files live in public/media and are served from disk (as before).
// - With BLOB_READ_WRITE_TOKEN: new uploads go to Vercel Blob under the same pathname (`media/<path>`),
//   and `/media/<path>` requests that are not on disk are redirected to the Blob store.
//   Existing files are copied once with `npm run media:upload`.
// On Vercel, add a rewrite `/media/:path*` → `<BLOB_BASE_URL>/media/:path*` (see README) so no redirect is needed.
import { existsSync } from 'node:fs'
import fs from 'node:fs/promises'
import path from 'node:path'
import { fileURLToPath } from 'node:url'

export const MEDIA_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'public', 'media')

const token = () => process.env.BLOB_READ_WRITE_TOKEN || ''
export const blobEnabled = () => Boolean(token())

/**
 * Public base URL of the Blob store, e.g. https://abc123.public.blob.vercel-storage.com.
 * BLOB_BASE_URL wins; otherwise derived from the token (vercel_blob_rw_<storeId>_<secret>).
 */
export function blobBaseUrl() {
  if (process.env.BLOB_BASE_URL) return process.env.BLOB_BASE_URL.replace(/\/+$/, '')
  const storeId = token().split('_')[3]
  return storeId ? `https://${storeId.toLowerCase()}.public.blob.vercel-storage.com` : ''
}

/** `/media/a/b.webp` → absolute path in public/media, or null if it escapes the folder. */
export function localPath(publicPath) {
  if (typeof publicPath !== 'string' || !publicPath.startsWith('/media/')) return null
  const abs = path.resolve(MEDIA_DIR, '.' + decodeURIComponent(publicPath.slice('/media'.length)))
  return abs.startsWith(MEDIA_DIR + path.sep) ? abs : null
}

/** `/media/a/b.webp` → URL in the Blob store. */
export const blobUrl = (publicPath) => `${blobBaseUrl()}${publicPath}`

/**
 * Stores a file and returns its public path (`/media/<rel>`).
 * @param {string} rel path under media/, e.g. "uploads/gallery/x.webp"
 * @param {Buffer} data
 * @param {string} contentType
 */
export async function saveMedia(rel, data, contentType) {
  const clean = rel.replace(/^\/+/, '')
  if (blobEnabled()) {
    const { put } = await import('@vercel/blob')
    await put(`media/${clean}`, data, {
      access: 'public',
      contentType,
      addRandomSuffix: false,
      allowOverwrite: true,
      cacheControlMaxAge: 60 * 60 * 24 * 365,
      token: token(),
    })
  } else {
    const abs = path.join(MEDIA_DIR, clean)
    await fs.mkdir(path.dirname(abs), { recursive: true })
    await fs.writeFile(abs, data)
  }
  return `/media/${clean}`
}

/** Reads a stored file (disk first, then Blob). Returns null when missing. */
export async function readMedia(publicPath) {
  const abs = localPath(publicPath)
  if (abs && existsSync(abs)) return fs.readFile(abs)
  if (!blobEnabled()) return null
  const r = await fetch(blobUrl(publicPath))
  return r.ok ? Buffer.from(await r.arrayBuffer()) : null
}

/** Deletes stored files; returns how many were removed. Only paths under /media/uploads/ can be deleted. */
export async function deleteMedia(publicPaths) {
  const ok = publicPaths.filter((p) => typeof p === 'string' && p.startsWith('/media/uploads/') && localPath(p))
  let n = 0
  for (const p of ok) {
    const abs = localPath(p)
    if (abs && existsSync(abs)) {
      await fs.unlink(abs)
      n++
    }
  }
  if (blobEnabled() && ok.length) {
    const { del } = await import('@vercel/blob')
    await del(
      ok.map((p) => blobUrl(p)),
      { token: token() },
    ).catch(() => undefined)
    n = Math.max(n, ok.length)
  }
  return n
}

/**
 * For `/media/...` requests not found on disk: redirect to the Blob store (when enabled).
 * Returns true when handled.
 */
export function redirectMissingMedia(pathname, res) {
  if (!pathname.startsWith('/media/') || !blobEnabled()) return false
  const abs = localPath(pathname)
  if (!abs || existsSync(abs)) return false
  res.writeHead(302, { Location: blobUrl(pathname), 'Cache-Control': 'public, max-age=3600' })
  res.end()
  return true
}
