import { Injectable } from '@angular/core';
import { throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
import { Apollo, gql } from 'apollo-angular';
import { FeatureFlag } from 'src/app/model/entities/feature-flag';

@Injectable({
  providedIn: 'root',
})
export class FeatureFlagService {
  constructor(private apollo: Apollo) {}

  get(key: string): Promise<boolean> {
    return new Promise((resolve, reject) => {
      this.apollo
        .query<{ featureFlags: FeatureFlag[] }>({
          query: gql`
            query getFeatureFlag($key: String!) {
              featureFlags(key: $key) {
                key
                value
              }
            }
          `,
          variables: {
            key,
          },
        })
        .pipe(
          catchError(err => {
            throw err;
          })
        )
        .pipe(map(result => result.data.featureFlags[0]))
        .pipe(
          catchError(err => {
            reject(err);
            return throwError(() => err);
          })
        )
        .subscribe(setting => {
          resolve(setting ? setting.value : false);
        });
    });
  }

  set(key: string, value: boolean): Promise<void> {
    return new Promise((resolve, reject) => {
      this.apollo
        .mutate<{ setting: { change: FeatureFlag } }>({
          mutation: gql`
            mutation changeFeatureFlag($input: FeatureFlagInput!) {
              featureFlag {
                change(input: $input) {
                  key
                  value
                }
              }
            }
          `,
          variables: {
            input: {
              key: key,
              value: value,
            },
          },
        })
        .pipe(
          catchError(err => {
            throw err;
          })
        )
        .pipe(map(result => result.data?.setting.change))
        .pipe(
          catchError(err => {
            reject(err);
            return throwError(() => err);
          })
        )
        .subscribe(() => {
          resolve();
        });
    });
  }
}
