import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { queryFlowTemplateApi } from '@/api/capability/flow';
import { getAllTaskPoolApi, getTaskPoolApi } from '@/api/task/taskpool';
import { FLOW_TEMPLATE_PUBLIC_STATUS, FLOW_USE_STATUS } from '@/utils/enum/flow';

interface Template {
  templateName?: string;
  templateCode?: string;
  [k: string]: any;
}

const fetchPoolData = async () => {
  try {
    const poolRes: any = await getAllTaskPoolApi({ bCurrent: false });
    if (poolRes.code !== 200 || !Array.isArray(poolRes.data) || poolRes.data.length === 0) {
      return { pools: [], versions: [], data: null };
    }
    const pools = poolRes.data.reverse().map((pool: any) => {
      return {
        ...pool,
        versions: (pool.versions || []).reverse().map((v: string) => ({
          poolName: pool.poolName,
          poolVersion: v,
          value: v,
        })),
      };
    });
    const firstPool = pools[0];

    if (!Array.isArray(firstPool.versions) || firstPool.versions.length === 0) {
      return { pools, versions: [], data: null };
    }
    const versions = firstPool.versions;
    const firstVersion = versions[0];

    const dataRes: any = await getTaskPoolApi({
      poolName: firstVersion.poolName,
      version: firstVersion.poolVersion,
    });

    return { pools, versions, data: dataRes };
  } catch {
    return { pools: [], versions: [], data: null };
  }
};

let earlyPoolDataPromise: Promise<{ pools: any[]; versions: any[]; data: any }> | null =
  fetchPoolData();

export const resetEarlyPoolData = () => {
  earlyPoolDataPromise = null;
};

export const getEarlyPoolData = (forceRefresh = false) => {
  if (forceRefresh || !earlyPoolDataPromise) {
    earlyPoolDataPromise = fetchPoolData();
  }
  return earlyPoolDataPromise;
};

export const useTaskStore = defineStore('task', () => {
  const templates = ref<Template[]>([]);
  const loaded = ref(false);
  let pendingPromise: Promise<Template[]> | null = null;

  const options = computed(() =>
    templates.value.map((item) => ({
      label: item.templateName || '',
      value: item.templateCode || '',
    }))
  );

  const fetchTemplates = async (force = false) => {
    if (!force && loaded.value && templates.value.length) return templates.value;
    if (pendingPromise) return pendingPromise;

    pendingPromise = (async () => {
      try {
        const req = {
          current: 1,
          size: 99999,
          type: FLOW_TEMPLATE_PUBLIC_STATUS.PUBLIC,
          templateStatus: FLOW_USE_STATUS.USED,
        };
        const res: any = await queryFlowTemplateApi(req);
        if (res && res.code === 200) {
          const list = res.data?.data || res.data || [];
          templates.value = Array.isArray(list) ? list : [];
        } else {
          templates.value = [];
        }
        loaded.value = true;
      } catch {
        templates.value = [];
        loaded.value = true;
      } finally {
        pendingPromise = null;
      }
      return templates.value;
    })();

    return pendingPromise;
  };

  return { templates, options, fetchTemplates, loaded };
});
