import { sendCommand } from "./client";
import { pickCase } from "./normalize";
export function hydrateWorkspace(password: string): Promise<unknown> {
  return sendCommand<unknown>({
    action: "db.hydrate_workspace",
    payload: { password },
  });
}

type RuntimeConfigRaw = {
  vaultDirectory?: string;
  VaultDirectory?: string;
};

type RuntimeConfig = {
  vaultDirectory: string;
};

type PersistOptions = {
  keepalive?: boolean;
};

async function getRuntimeConfig(
  options: PersistOptions = {},
): Promise<RuntimeConfig> {
  const data = await sendCommand<RuntimeConfigRaw>(
    {
      action: "config.get",
    },
    options,
  );

  return {
    vaultDirectory: pickCase(data, "vaultDirectory", "VaultDirectory", ""),
  };
}

export async function unlockVaultWorkspace(password: string): Promise<void> {
  const config = await getRuntimeConfig();
  const loaded = await sendCommand<boolean>({
    action: "vault.load_all",
    payload: {
      password,
      vaultDirectory: config.vaultDirectory,
    },
  });

  if (!loaded) {
    throw new Error("Incorrect vault password.");
  }

  await sendCommand<unknown>({
    action: "db.hydrate_workspace",
    payload: {
      password,
    },
  });
}

export async function persistAndClearVault(
  password: string,
  options: PersistOptions = {},
): Promise<void> {
  const config = await getRuntimeConfig(options);

  await sendCommand<boolean>(
    {
      action: "vault.rebuild_all",
      payload: {
        password,
        vaultDirectory: config.vaultDirectory,
      },
    },
    options,
  );

  await sendCommand<boolean>(
    {
      action: "vault.clear_data_directory",
      payload: {},
    },
    options,
  );
}
