import * as DocumentPicker from "expo-document-picker";
import type { CodexAuth } from "@/types/codex";

export async function pickAndReadCodexAuth(): Promise<CodexAuth> {
  const result = await DocumentPicker.getDocumentAsync({
    type: "application/json",
    copyToCacheDirectory: true,
  });

  if (result.canceled) throw new Error("PICKER_CANCELLED");

  const { uri } = result.assets[0];
  const response = await fetch(uri);
  const text = await response.text();

  let parsed: Record<string, unknown>;
  try {
    parsed = JSON.parse(text);
  } catch {
    throw new Error("INVALID_JSON");
  }

  const tokens = parsed["tokens"] as Record<string, unknown> | undefined;
  const accessToken = (tokens?.["access_token"] ?? parsed["accessToken"]) as string | undefined;
  const accountId = (tokens?.["account_id"] ?? parsed["accountId"]) as string | undefined;

  if (!accessToken || typeof accessToken !== "string") {
    throw new Error("MISSING_ACCESS_TOKEN");
  }

  return { accessToken, accountId };
}
