import {
  createDatabase,
  createLocalDatabase,
  IsomorphicBridge,
} from "@tinacms/datalayer";
import { RedisLevel } from "upstash-redis-level";
import { Redis } from "@upstash/redis";

const isLocal = process.env.TINA_PUBLIC_IS_LOCAL === "true";
const branch = process.env.TINA_GIT_BRANCH || "main";

function createProductionDatabase() {
  const kvUrl = process.env.KV_REST_API_URL;
  const kvToken = process.env.KV_REST_API_TOKEN;

  if (!kvUrl || !kvToken) {
    // During tinacms build (schema generation), env vars may not be available.
    // Fall back to local database for the build step.
    return createLocalDatabase();
  }

  return createDatabase({
    gitProvider: {
      onPut: async () => {},
      onDelete: async () => {},
    },
    databaseAdapter: new RedisLevel<string, Record<string, unknown>>({
      redis: new Redis({
        url: kvUrl,
        token: kvToken,
      }) as any,
      debug: process.env.DEBUG === "true" || false,
    }),
    bridge: new IsomorphicBridge(process.cwd(), {
      gitRoot: process.cwd(),
      author: {
        name: "TinaCMS",
        email: "cms@linumiq.com",
      },
      commitMessage: "Content updated via TinaCMS",
    }),
    namespace: branch,
  });
}

export default isLocal ? createLocalDatabase() : createProductionDatabase();
