import { env } from "@/lib/env";

type PdfMetaAsset = {
  kind: "pdf";
  pdfPath: string;
  previewPath: string | null;
  page: number;
};

const PDF_META_PREFIX = "pdfmeta|";

function normalizeRelative(path: string) {
  return path.replace(/^\/+/, "");
}

function toAppAssetUrl(relativePath: string) {
  const rel = normalizeRelative(relativePath);
  const appUrl = (env.appUrl || "").trim();

  if (/^https?:\/\//i.test(appUrl)) {
    return `${appUrl.replace(/\/+$/, "")}/${rel}`;
  }

  const basePath = appUrl ? `/${appUrl.replace(/^\/+|\/+$/g, "")}` : "";
  return `${basePath}/${rel}`.replace(/\/+/g, "/");
}

function toPublicAssetUrl(path: string | null | undefined) {
  if (!path) return null;
  if (path.startsWith("local-thumbnails/")) {
    return toAppAssetUrl(path);
  }
  return `${env.supabaseUrl}/storage/v1/object/public/thumbnails/${path}`;
}

function parsePdfMetaAsset(path: string | null | undefined): PdfMetaAsset | null {
  if (!path || !path.startsWith(PDF_META_PREFIX)) return null;
  const raw = path.slice(PDF_META_PREFIX.length);
  const [pageRaw, encodedPdfPath, encodedPreviewPath] = raw.split("|");
  const page = Number(pageRaw);
  const pdfPath = encodedPdfPath ? decodeURIComponent(encodedPdfPath) : "";
  const previewPath = encodedPreviewPath ? decodeURIComponent(encodedPreviewPath) : "";

  if (!Number.isInteger(page) || page < 1 || !pdfPath) return null;

  return {
    kind: "pdf",
    pdfPath,
    previewPath: previewPath || null,
    page,
  };
}

export function encodePdfMetaAsset(input: {
  pdfPath: string;
  previewPath?: string | null;
  page?: number;
}) {
  const page = Math.max(1, Number(input.page ?? 1) || 1);
  return `${PDF_META_PREFIX}${page}|${encodeURIComponent(input.pdfPath)}|${encodeURIComponent(
    input.previewPath ?? "",
  )}`;
}

export function isPdfMetaAsset(path: string | null | undefined) {
  return Boolean(parsePdfMetaAsset(path));
}

export function getPublicSourceAssetUrl(path: string | null | undefined) {
  const pdfMeta = parsePdfMetaAsset(path);
  if (pdfMeta) {
    const base = toPublicAssetUrl(pdfMeta.pdfPath);
    return base ? `${base}#page=${pdfMeta.page}` : null;
  }
  return toPublicAssetUrl(path);
}

export function getPublicThumbnailUrl(path: string | null | undefined) {
  const pdfMeta = parsePdfMetaAsset(path);
  if (pdfMeta) {
    return toPublicAssetUrl(pdfMeta.previewPath);
  }
  return toPublicAssetUrl(path);
}
