import { defineStore } from 'pinia'
import type { ConfigEnvelope, ConfigSection, OpsConfig } from '@/types/config'
import { getConfig, putConfig } from '@/api/config'
import { normalizeOpsConfig } from '@/utils/opsMonitorConfig'

interface ConfigState {
  cache: Partial<Record<ConfigSection, ConfigEnvelope>>
  loading: Partial<Record<ConfigSection, boolean>>
}

export const useConfigStore = defineStore('config', {
  state: (): ConfigState => ({ cache: {}, loading: {} }),
  actions: {
    async load<T>(section: ConfigSection, force = false): Promise<ConfigEnvelope<T>> {
      if (!force && this.cache[section]) return this.cache[section] as ConfigEnvelope<T>
      this.loading[section] = true
      try {
        const env = await getConfig<T>(section)
        if (section === 'ops' && env.payload) {
          env.payload = normalizeOpsConfig(env.payload as unknown as OpsConfig) as T
        }
        this.cache[section] = env as ConfigEnvelope
        return env
      } finally {
        this.loading[section] = false
      }
    },
    async save<T>(section: ConfigSection, payload: T): Promise<ConfigEnvelope<T>> {
      this.loading[section] = true
      try {
        const body = section === 'ops'
          ? (normalizeOpsConfig(payload as unknown as OpsConfig) as T)
          : payload
        const env = await putConfig<T>(section, body)
        this.cache[section] = env as ConfigEnvelope
        return env
      } finally {
        this.loading[section] = false
      }
    }
  }
})
