import { createDirectus, authentication, rest } from "@directus/sdk";
import { appConfig } from "@/config/env";

const createBrowserStorage = () => {
  if (typeof window === "undefined" || !window.localStorage) {
    const memoryStore = new Map();
    return {
      get: async () => null,
      set: async (value) => value,
    };
  }

  return {
    get: async () => {
      const rawValue = window.localStorage.getItem("mkt_directus_auth");
      return rawValue ? JSON.parse(rawValue) : null;
    },
    set: async (value) => {
      if (!value) {
        window.localStorage.removeItem("mkt_directus_auth");
        return value;
      }

      window.localStorage.setItem("mkt_directus_auth", JSON.stringify(value));
      return value;
    },
  };
};

export const createDirectusClient = () => {
  return createDirectus(appConfig.directusBaseUrl)
    .with(rest())
    .with(
      authentication("json", {
        storage: createBrowserStorage(),
      }),
    );
};

export default createDirectusClient;
