import type { PluginContext } from '../domain/plugin-context';

import { acceptHMRUpdate, defineStore } from 'pinia';

import { parsePluginContext } from '../domain/plugin-context';

export interface PluginContextState {
  context: null | PluginContext;
  error: string;
  status: 'error' | 'initializing' | 'ready';
}

function initialState(): PluginContextState {
  return { status: 'initializing', context: null, error: '' };
}

export const usePluginContextStore = defineStore('plugin-context', {
  state: initialState,
  actions: {
    initialize(options: unknown): boolean {
      try {
        this.context = parsePluginContext(options);
        this.status = 'ready';
        this.error = '';
        return true;
      } catch {
        this.context = null;
        this.status = 'error';
        this.error = '插件运行上下文无效';
        return false;
      }
    },
    reset() {
      this.$state = initialState();
    },
  },
});

const hot = import.meta.hot;
if (hot) {
  hot.accept(acceptHMRUpdate(usePluginContextStore, hot));
}
