import type { Account } from "@prisma/client";
import { getOrCreateSettings } from "@/lib/user-settings";
import { getActiveAccountProfile } from "@/lib/account-context";
import {
  accountHasThreadsToken,
  ensureValidAccessTokenForAccount,
  getThreadsCredentials,
} from "@/lib/threads-api";

export type ResolvedThreadsCredentials = NonNullable<
  ReturnType<typeof getThreadsCredentials>
>;

/**
 * 取得「目前帳號」的官方 API 憑證。
 * App ID / App Secret 為全域共用（存在 Setting），
 * access token / user id 為每個帳號各自的（存在 Account）。
 * 會視需要刷新長效 token 並寫回該帳號。
 */
export async function getActiveThreadsCredentials(): Promise<ResolvedThreadsCredentials | null> {
  const settings = await getOrCreateSettings();
  const account = await getActiveAccountProfile();
  if (!account) return null;

  const accessToken = await ensureValidAccessTokenForAccount(account);
  return getThreadsCredentials(settings, account, accessToken);
}

export function describeThreadsConnection(account: Account | null) {
  return {
    connected: accountHasThreadsToken(account),
    threadsUserId: account?.threadsUserId ?? null,
    threadsTokenExpiresAt: account?.threadsTokenExpiresAt?.toISOString() ?? null,
  };
}
