import axios from 'axios'
import { ILocalConfig } from '../../types/config.ts'

class LocalConfig {
  // Static property to hold the single instance of LocalCache
  private static instance: LocalConfig | null = null

  private config: ILocalConfig

  // Private constructor to prevent direct instantiation
  private constructor() {
    // Set default config
    this.config = {
      SIGIT_BLOSSOM: 'https://blossom.sigit.io'
    }
  }

  // Method to initialize the database
  private async init() {
    axios
      .get<ILocalConfig>('/config.json')
      .then((response) => {
        console.log('response', response)

        if (typeof response.data === 'object') {
          this.config = response.data
        } else {
          throw 'Failed to load config.json: File not found'
        }
      })
      .catch((error) => {
        console.error('Failed to load config.json:', error)
        console.warn('Default config will be used.')
      })
  }

  // Static method to get the single instance of LocalCache
  public static getInstance(): LocalConfig {
    // If the instance doesn't exist, create it
    if (!LocalConfig.instance) {
      LocalConfig.instance = new LocalConfig()
      LocalConfig.instance.init()
    }
    // Return the single instance of LocalCache
    return LocalConfig.instance
  }

  public getConfig() {
    return this.config
  }
}

// Export the single instance of LocalCache
export const localConfig = LocalConfig.getInstance()
