import { usePage } from "@inertiajs/react";

interface FlagList {
  id: string;
  enabled: boolean;
}

class FeatureFlags {
  private flagList: FlagList[];

  constructor() {
    try {
      const page = usePage();
      const { props } = page as unknown as {
        props: { data: { flags: FlagList[] } };
      };
      const { data } = props;
      const { flags } = data;

      this.flagList = flags;
    } catch (error) {
      console.error("Could not find feature flags");
      console.log(error);
      this.flagList = [];
    }
  }

  /**
   * Detects if a specified flag exists and is enabled.
   * @param flag The flag identifier,
   * @returns if the flag exists and is enabled
   */
  public hasFlag(flag: string): boolean {
    const hasFlagListed = this.flagList.find((item) => item.id === flag);
    if (hasFlagListed === undefined) {
      return false;
    }

    return hasFlagListed.enabled;
  }
}

let flags: FeatureFlags | null = null;

/**
 * Hook for handling feature flags.
 */
export function useFeatureFlags(): FeatureFlags {
  if (flags === null) {
    flags = new FeatureFlags();
  }

  return flags;
}
