import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
import {
  CONFIGURATION_PARSER_FN,
  ConfigurationPropertyValueType,
  EConfigurationProperty,
} from './helpers/configuration-type.helper';
import { OPTIONAL_CONFIGURATION_PROPERTIES } from './services/configuration-validation/configuration-validation.service';

// Exceptions
export class ConfigurationNotFoundException extends Error {}

@Entity()
export class Configuration extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column({ default: null })
  value: string;

  static async get<T extends EConfigurationProperty>(
    name: T
  ): Promise<ConfigurationPropertyValueType[T] | null> {
    const configuration = await this.findOne({ where: { name } });

    if (configuration === undefined) {
      if (!OPTIONAL_CONFIGURATION_PROPERTIES.includes(name)) {
        throw new ConfigurationNotFoundException(
          `Configuration entity: could not find configuration property "${name}"`
        );
      } else {
        return null;
      }
    }

    return CONFIGURATION_PARSER_FN[name](configuration.value);
  }
}
