import * as t from 'io-ts';
import { join } from 'path';

import { CLI_TERSE_ERROR } from '@alwaysai/alwayscli';
import { AuthenticationStorage } from '@alwaysai/cloud-api';
import { ConfigFile } from '@alwaysai/config-nodejs';
import { LOCAL_AAI_CFG_DIR } from '../paths';
import { getSystemId } from './system-id';

const credentialsJsonCodec = t.record(t.string, t.any);

export function CredentialsJsonFile(filePath?: string) {
  const systemId = getSystemId();
  const path =
    filePath ??
    join(
      LOCAL_AAI_CFG_DIR,
      `alwaysai.credentials${
        systemId !== 'production' ? '.' + systemId : ''
      }.json`
    );
  const configFile = ConfigFile({
    path,
    codec: credentialsJsonCodec,
    ENOENT: {
      code: CLI_TERSE_ERROR,
      message: `File not found ${path}. Please ensure the ${LOCAL_AAI_CFG_DIR} folder exists in the home directory and has read and write access for the current user`
    },
    EACCES: {
      code: CLI_TERSE_ERROR,
      message: `Please ensure the permissions on ${path} and ${LOCAL_AAI_CFG_DIR} include read and write access for the current user.`
    },
    initialValue: {}
  });

  configFile.initialize();

  const authenticationStorage: AuthenticationStorage = {
    setItem(key: string, value: string) {
      configFile.update((config) => {
        config[key] = value;
      });
    },
    getItem(key: string) {
      return configFile.read()[key] || '';
    },
    removeItem(key: string) {
      configFile.update((config) => {
        delete config[key];
      });
    },
    clear() {
      configFile.write({});
    }
  };

  return authenticationStorage;
}
