import { createAuthClient } from "better-auth/react";
import { organizationClient } from "better-auth/client/plugins";
import { expoClient } from "@better-auth/expo/client";
import * as SecureStore from "expo-secure-store";
import { env } from "@haushaltsApp/env/native";

// expoClient plugin stores session token under "<storagePrefix>.session_token"
const TOKEN_KEY = "haushaltsapp.session_token";

export const authClient = createAuthClient({
  baseURL: env.EXPO_PUBLIC_SERVER_URL,
  fetchOptions: {
    onSuccess: (ctx) => {
      const token = ctx.response.headers.get("set-auth-token");
      if (token) {
        SecureStore.setItemAsync(TOKEN_KEY, token);
      }
    },
    auth: {
      type: "Bearer",
      token: () => SecureStore.getItem(TOKEN_KEY) ?? "",
    },
  },
  plugins: [
    expoClient({
      scheme: "haushaltsApp",
      storagePrefix: "haushaltsapp",
      storage: SecureStore,
    }),
    organizationClient(),
  ],
});

export const { signIn, signUp, signOut, useSession } = authClient;
