const PENDING_KEY = "threads_oauth_pending";
const RETURN_MESSAGE_KEY = "haixun.threads_oauth_return_message";

export type ThreadsOAuthReturn = {
  status: "ok" | "error";
  accountId?: string;
  message: string;
};

export function markOAuthPending(accountId: string) {
  sessionStorage.setItem(
    PENDING_KEY,
    JSON.stringify({ at: Date.now(), account_id: accountId })
  );
}

export function clearOAuthPending() {
  sessionStorage.removeItem(PENDING_KEY);
}

export function pendingOAuthMessage(): string | null {
  const raw = sessionStorage.getItem(PENDING_KEY);
  if (!raw) return null;
  try {
    const pending = JSON.parse(raw) as { at?: number };
    if (!pending.at || Date.now() - pending.at > 15 * 60 * 1000) {
      clearOAuthPending();
      return null;
    }
    return "Threads 授權進行中：請在 Meta 頁面完成登入，並等待自動導回巡樓（本機 ngrok 若出現 Visit Site 請點進去）。";
  } catch {
    clearOAuthPending();
    return null;
  }
}

export function stashOAuthReturnMessage(message: string) {
  sessionStorage.setItem(RETURN_MESSAGE_KEY, message);
}

export function consumeOAuthReturnMessage(): string | null {
  const message = sessionStorage.getItem(RETURN_MESSAGE_KEY);
  if (message) sessionStorage.removeItem(RETURN_MESSAGE_KEY);
  return message;
}

export function parseOAuthReturn(search: string): ThreadsOAuthReturn | null {
  const params = new URLSearchParams(search);
  const status = params.get("threads_oauth");
  if (status !== "ok" && status !== "error") return null;

  const accountId = params.get("account_id") || undefined;
  if (status === "ok") {
    return {
      status: "ok",
      accountId,
      message: accountId ? "Threads OAuth 授權成功，帳號已連線。" : "Threads OAuth 授權成功。",
    };
  }

  const detail = decodeURIComponent((params.get("message") || "未知錯誤").replace(/\+/g, " "));
  return { status: "error", accountId, message: `Threads OAuth 失敗：${detail}` };
}

export function stripOAuthReturnFromUrl() {
  const params = new URLSearchParams(window.location.search);
  if (!params.has("threads_oauth")) return false;

  params.delete("threads_oauth");
  params.delete("account_id");
  params.delete("message");
  const query = params.toString();
  const next = `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`;
  window.history.replaceState({}, "", next);
  return true;
}