import {
  createDatabase,
  createLocalDatabase,
  FilesystemBridge,
} from "@tinacms/datalayer";
import { RedisLevel } from "upstash-redis-level";
import { Redis } from "@upstash/redis";
import { GiteaGitProvider } from "./gitea-git-provider";

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

function createProductionDatabase() {
  const giteaUrl = process.env.GITEA_URL;
  const giteaToken = process.env.GITEA_TOKEN;
  const giteaOwner = process.env.GITEA_OWNER;
  const giteaRepo = process.env.GITEA_REPO;
  const kvUrl = process.env.KV_REST_API_URL;
  const kvToken = process.env.KV_REST_API_TOKEN;

  if (!giteaUrl || !giteaToken || !giteaOwner || !giteaRepo) {
    // 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: new GiteaGitProvider({
      owner: giteaOwner,
      repo: giteaRepo,
      token: giteaToken,
      branch,
      baseUrl: giteaUrl,
    }),
    databaseAdapter: new RedisLevel<string, Record<string, unknown>>({
      redis: new Redis({
        url: kvUrl || "http://localhost:8079",
        token: kvToken || "example_token",
      }) as any,
      debug: process.env.DEBUG === "true" || false,
    }),
    bridge: new FilesystemBridge(process.cwd()),
    namespace: branch,
  });
}

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