import { adminFetch } from "./adminApi";

export type LinkType = "stamp" | "article" | "music";

const LINK_CFG: Record<LinkType, { path: (id: string) => string; urlKey: string }> = {
  stamp: { path: (id) => `/stamps/${id}/qrcode`, urlKey: "collectUrl" },
  article: { path: (id) => `/articles/${id}/qrcode`, urlKey: "articleUrl" },
  music: { path: (id) => `/music/${id}/qrcode`, urlKey: "musicUrl" },
};

export async function fetchItemUrl(type: LinkType, id: string): Promise<string> {
  const cfg = LINK_CFG[type];
  const data = await adminFetch<Record<string, string>>(cfg.path(id));
  return data[cfg.urlKey];
}

export async function copyText(text: string) {
  try {
    await navigator.clipboard.writeText(text);
  } catch {
    const ta = document.createElement("textarea");
    ta.value = text;
    ta.style.position = "fixed";
    ta.style.opacity = "0";
    document.body.appendChild(ta);
    ta.select();
    document.execCommand("copy");
    document.body.removeChild(ta);
  }
}

export async function copyItemLink(type: LinkType, id: string): Promise<string> {
  const url = await fetchItemUrl(type, id);
  await copyText(url);
  return url;
}
