import { defineStore } from 'pinia';
import { ref } from 'vue';
import { tealService } from './teal.service';
import type { TealEntry } from './teal.types';

export interface TealVersion {
  id: number;
  projectId: number;
  versionNumber: number;
  effectiveDate: string;
  status: string;
  entryCount?: number;
}

export const useTealStore = defineStore('teal', () => {
  const loading = ref(false);
  const versions = ref<TealVersion[]>([]);
  const entries = ref<TealEntry[]>([]);
  const selectedProjectId = ref<number | null>(null);

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

  async function fetchActive(projectId: number) {
    loading.value = true;
    try {
      const { data } = await tealService.getActive(projectId);
      entries.value = (data as any).items ?? data;
    } finally {
      loading.value = false;
    }
  }

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

  return {
    loading,
    versions,
    entries,
    selectedProjectId,
    fetchVersions,
    fetchActive,
    upload,
  };
});
