import { OrgConfigFeatureGate } from 'src/application/models';
import { FeatureGates } from 'src/application/models/featureGates';

type EnviveConfigServiceProps = {
  baseUrl: string;
  apiKey: string;
  userId: string;
  namespace: string;
  source: string;
};

export type EnviveServiceConfig = {
  org: {
    org: {
      id: string;
      short_name: string;
      display_name: string;
      domain: string;
      status: string;
      created_at: string;
      updated_at: string;
    };
  };
  gates: OrgConfigFeatureGate[];
};

export class EnviveConfigService {
  private readonly baseUrl: string;

  private readonly apiKey: string;

  private readonly userId: string;

  private readonly namespace: string;

  private readonly source: string;

  private response: EnviveServiceConfig | null = null;

  constructor({ baseUrl, apiKey, userId, namespace, source }: EnviveConfigServiceProps) {
    this.baseUrl = baseUrl;
    this.apiKey = apiKey;
    this.userId = userId;
    this.namespace = namespace;
    this.source = source;
  }

  async getEnviveConfig(): Promise<EnviveServiceConfig> {
    if (this.response !== null) {
      return this.response;
    }
    const queryParams = new URLSearchParams({
      namespace: this.namespace,
      source: this.source,
      user_id: this.userId,
      include_experiments: 'default',
      include_feature_gates: Object.values(FeatureGates)
        .map(featureGate => featureGate.toString())
        .join(','),
    });
    const response = await fetch(`${this.baseUrl}/v1/org/config?${queryParams.toString()}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${this.apiKey}`,
      },
    });
    const data = (await response.json()) as EnviveServiceConfig;
    this.response = data;
    return data;
  }
}
