import { THREADS_MAX_CHARS } from "@/lib/utils";
import { threadsGraphGet, threadsGraphPost } from "./client";
import type { ThreadsApiCredentials, ThreadsPublishResult } from "./types";
import { publishViaThreadsApi } from "./publish";

export interface ThreadsApiReply {
  id: string;
  text?: string;
  username?: string;
  permalink?: string;
  timestamp?: string;
  like_count?: number;
  parent_id?: string;
}

interface ThreadsRepliesResponse {
  data?: ThreadsApiReply[];
}

export async function getMediaRepliesViaThreadsApi(
  credentials: ThreadsApiCredentials,
  mediaId: string,
  limit = 25
): Promise<ThreadsApiReply[]> {
  const json = await threadsGraphGet<ThreadsRepliesResponse>(`/${mediaId}/replies`, {
    access_token: credentials.accessToken,
    fields: "id,text,username,permalink,timestamp,like_count,parent_id",
    limit: String(limit),
  });

  return json.data ?? [];
}

export async function getOwnRepliesViaThreadsApi(
  credentials: ThreadsApiCredentials,
  limit = 25
): Promise<ThreadsApiReply[]> {
  const json = await threadsGraphGet<ThreadsRepliesResponse>(
    `/${credentials.userId}/replies`,
    {
      access_token: credentials.accessToken,
      fields: "id,text,username,permalink,timestamp,like_count,parent_id",
      limit: String(limit),
    }
  );

  return json.data ?? [];
}

export async function replyViaThreadsApi(
  credentials: ThreadsApiCredentials,
  input: { replyToId: string; text: string }
): Promise<ThreadsPublishResult> {
  if (input.text.length > THREADS_MAX_CHARS) {
    return { success: false, error: `回覆超過 ${THREADS_MAX_CHARS} 字上限`, method: "api" };
  }

  return publishViaThreadsApi(credentials, {
    text: input.text,
    replyToId: input.replyToId,
  });
}

export async function hideReplyViaThreadsApi(
  credentials: ThreadsApiCredentials,
  replyId: string,
  hide = true
) {
  return threadsGraphPost<{ success?: boolean }>(`/${replyId}/manage_reply`, {
    access_token: credentials.accessToken,
    hide: hide ? "true" : "false",
  });
}
