import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import Constants from "expo-constants";
import { Platform } from "react-native";

import { getToken } from "@/auth/token";

export const getApiUrl = () => {
  const isDev = process.env.NODE_ENV === "development" || !process.env.NODE_ENV;
  const prodUrl = "https://your-production-api.com/api";
  if (!isDev) return prodUrl;

  if (Platform.OS === "web") {
    return process.env.EXPO_PUBLIC_BACKEND_URL || "http://localhost:5000/api";
  }

  try {
    const debuggerHost =
      Constants.expoConfig?.hostUri ||
      Constants.manifest2?.extra?.expoGo?.debuggerHost;

    if (debuggerHost) {
      const hostIp = debuggerHost.split(":")[0];
      return `http://${hostIp}:5000/api`;
    }
  } catch (error) {
    console.error("Failed to get debuggerHost:", error);
  }

  if (process.env.EXPO_PUBLIC_API_URL) {
    return process.env.EXPO_PUBLIC_API_URL;
  }

  return "http://192.168.1.X:5000/api";
};

export const baseApi = createApi({
  reducerPath: "api",
  baseQuery: fetchBaseQuery({
    baseUrl: getApiUrl(),
    prepareHeaders: (headers) => {
      headers.set("accept", "application/json");
      const token = getToken();
      if (token) {
        headers.set("authorization", `Bearer ${token}`);
      }
      return headers;
    },
  }),
  refetchOnFocus: false,
  refetchOnReconnect: true,
  tagTypes: ["Users", "Todos", "UserLogs"],
  endpoints: () => ({}),
});
