import { defineStore } from 'pinia';
import { ref } from 'vue';
import { wbsService } from './wbs.service';
import type { WbsVersion, WbsNode } from './wbs.types';

export const useWbsStore = defineStore('wbs', () => {
  const loading = ref(false);
  const versions = ref<WbsVersion[]>([]);
  const nodes = ref<WbsNode[]>([]);
  const selectedProjectId = ref<number | null>(null);
  const selectedVersion = ref<WbsVersion | null>(null);

  async function fetchVersions(projectId: number) {
    loading.value = true;
    try {
      const { data } = await wbsService.getVersions(projectId);
      versions.value = (data as any).items ?? data;
    } finally {
      loading.value = false;
    }
  }

  async function fetchNodes(projectId: number, versionNumber: number) {
    loading.value = true;
    try {
      const { data } = await wbsService.getVersion(projectId, versionNumber);
      nodes.value = (data as any).nodes ?? (data as any).items ?? data;
    } finally {
      loading.value = false;
    }
  }

  async function uploadWbs(projectId: number, file: File, effectiveDate: string) {
    loading.value = true;
    try {
      await wbsService.uploadP6(projectId, file, effectiveDate);
      await fetchVersions(projectId);
    } finally {
      loading.value = false;
    }
  }

  async function activateVersion(projectId: number, versionNumber: number) {
    loading.value = true;
    try {
      await wbsService.activateVersion(projectId, versionNumber);
      await fetchVersions(projectId);
    } finally {
      loading.value = false;
    }
  }

  return {
    loading,
    versions,
    nodes,
    selectedProjectId,
    selectedVersion,
    fetchVersions,
    fetchNodes,
    uploadWbs,
    activateVersion,
  };
});
