import {
  ConfigFileSchema,
  ConfigFileSchemaReturnType
} from '@alwaysai/config-nodejs';
import Ajv, { JSONSchemaType } from 'ajv';
import { SYSTEM_IDS, SystemId } from '../../constants';
import { getLocalDeviceConfigFilePath } from '../../infrastructure/device-paths';

export type DeviceTokens = {
  deviceUuid: string;
  accessToken: string;
  refreshToken: string;
  idToken: string;
};

export type DeviceConfig = {
  deviceUuid: string;
  systemId: SystemId;
} & DeviceTokens;

export const deviceConfigSchema: JSONSchemaType<DeviceConfig> = {
  type: 'object',
  properties: {
    systemId: {
      type: 'string',
      enum: SYSTEM_IDS
    },
    deviceUuid: {
      type: 'string'
    },
    accessToken: {
      type: 'string'
    },
    refreshToken: {
      type: 'string'
    },
    idToken: {
      type: 'string'
    }
  },
  required: [
    'systemId',
    'deviceUuid',
    'accessToken',
    'refreshToken',
    'idToken'
  ],
  additionalProperties: false
};

const ajv = new Ajv();

export const validateDeviceConfig = ajv.compile(deviceConfigSchema);

export function DeviceConfigFile(
  path?: string
): ConfigFileSchemaReturnType<DeviceConfig> {
  const filePath = path ?? getLocalDeviceConfigFilePath();
  const configFile = ConfigFileSchema<DeviceConfig>({
    path: filePath,
    validateFunction: validateDeviceConfig
  });

  return configFile;
}
