import axios, { AxiosInstance } from "axios";

export const auth = {
  async fetchAuthRedirectUri(api_url: string): Promise<{
    uri: string;
    callbackKey: string;
  }> {
    const client: AxiosInstance = axios.create({
      baseURL: api_url || "",
      timeout: 5000,
    });
    try {
      const res = await client.get("/v1/auth/uri");
      const d = res.data ?? {};
      const uri = d.data.uri;
      const callbackKey = d.data.callbackKey;
      if (typeof uri !== "string" || !uri)
        throw new Error("redirect uri missing from response");
      return {
        uri,
        callbackKey,
      };
    } catch (e) {
      throw new Error(
        `Failed to fetch auth redirect uri: ${(e as Error).message}`,
      );
    }
  },
};
