import { threadsGraphGet } from "./client";
import type { ThreadsApiCredentials } from "./types";

export type ThreadsInsightMetric =
  | "views"
  | "likes"
  | "replies"
  | "reposts"
  | "quotes"
  | "clicks"
  | "followers_count";

interface ThreadsInsightValue {
  value?: number;
}

interface ThreadsInsightItem {
  name?: ThreadsInsightMetric;
  total_value?: ThreadsInsightValue;
  values?: ThreadsInsightValue[];
}

interface ThreadsInsightsResponse {
  data?: ThreadsInsightItem[];
}

export type ThreadsInsights = Partial<Record<ThreadsInsightMetric, number>>;

export async function getMediaInsightsViaThreadsApi(
  credentials: ThreadsApiCredentials,
  mediaId: string,
  metrics: ThreadsInsightMetric[] = ["views", "likes", "replies", "reposts", "quotes"]
): Promise<ThreadsInsights> {
  const json = await threadsGraphGet<ThreadsInsightsResponse>(`/${mediaId}/insights`, {
    access_token: credentials.accessToken,
    metric: metrics.join(","),
  });

  const result: ThreadsInsights = {};
  for (const item of json.data ?? []) {
    if (!item.name) continue;
    const value = item.total_value?.value ?? item.values?.[0]?.value;
    if (typeof value === "number") result[item.name] = value;
  }
  return result;
}

export async function getProfileInsightsViaThreadsApi(
  credentials: ThreadsApiCredentials,
  metrics: ThreadsInsightMetric[] = ["views", "likes", "replies", "reposts", "quotes", "followers_count"]
): Promise<ThreadsInsights> {
  const json = await threadsGraphGet<ThreadsInsightsResponse>(
    `/${credentials.userId}/threads_insights`,
    {
      access_token: credentials.accessToken,
      metric: metrics.join(","),
    }
  );

  const result: ThreadsInsights = {};
  for (const item of json.data ?? []) {
    if (!item.name) continue;
    const value = item.total_value?.value ?? item.values?.[0]?.value;
    if (typeof value === "number") result[item.name] = value;
  }
  return result;
}
