import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { createClient, fetchExchange } from "urql";
import type { E2eState } from "../global-setup";

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const STATE_FILE = path.resolve(__dirname, "../.e2e-state.json");

interface MachineUserEnv {
  appUrl: string;
  graphqlEndpoint: string;
  token: string;
  graphqlClient: ReturnType<typeof createClient>;
}

function createGraphqlClient(graphqlEndpoint: string, authToken: string) {
  return createClient({
    url: graphqlEndpoint,
    fetchOptions: {
      headers: {
        Authorization: `Bearer ${authToken}`,
      },
    },
    exchanges: [fetchExchange],
  });
}

function loadState(): E2eState {
  if (!fs.existsSync(STATE_FILE)) {
    throw new Error("E2E state file not found. Make sure globalSetup has run successfully.");
  }
  return JSON.parse(fs.readFileSync(STATE_FILE, "utf-8")) as E2eState;
}

let cached: MachineUserEnv | null = null;
export function resolveTailorAuth(): MachineUserEnv {
  if (cached) return cached;

  const state = loadState();
  const graphqlClient = createGraphqlClient(state.graphqlEndpoint, state.token);

  cached = {
    appUrl: state.appUrl,
    graphqlEndpoint: state.graphqlEndpoint,
    token: state.token,
    graphqlClient,
  };
  return cached;
}
