"use client";

import { useQuery } from "@tanstack/react-query";
import type { BacklinkRecord } from "@/types/references";

interface UseBacklinksOptions {
  workspaceId: string | null;
  documentId: string | null;
  enabled?: boolean;
}

interface RawBacklink {
  id: string;
  source_page_id: string;
  source_block_id: string | null;
  alias: string | null;
  display_mode: string;
  is_previewable: boolean;
  created_at: string;
  updated_at: string;
  source_title: string | null;
}

const mapBacklink = (raw: RawBacklink): BacklinkRecord => ({
  id: raw.id,
  sourcePageId: raw.source_page_id,
  sourceBlockId: raw.source_block_id,
  alias: raw.alias,
  displayMode: (raw.display_mode as BacklinkRecord["displayMode"]) ?? "inline",
  isPreviewable: raw.is_previewable,
  createdAt: raw.created_at,
  updatedAt: raw.updated_at,
  sourceTitle: raw.source_title,
});

const fetchBacklinks = async (workspaceId: string, documentId: string): Promise<BacklinkRecord[]> => {
  const params = new URLSearchParams({
    workspaceId,
    pageId: documentId,
  });
  const response = await fetch(`/api/references/backlinks?${params.toString()}`);
  if (!response.ok) {
    const message = (await response.json().catch(() => null))?.error ?? "加载引用失败";
    throw new Error(message);
  }
  const payload = (await response.json()) as { backlinks: RawBacklink[] };
  return (payload.backlinks ?? []).map(mapBacklink);
};

export function useBacklinks({ workspaceId, documentId, enabled = true }: UseBacklinksOptions) {
  return useQuery({
    queryKey: ["page-backlinks", workspaceId, documentId],
    queryFn: () => {
      if (!workspaceId || !documentId) {
        throw new Error("缺少引用参数");
      }
      return fetchBacklinks(workspaceId, documentId);
    },
    enabled: Boolean(enabled && workspaceId && documentId),
    staleTime: 15_000,
  });
}
