import { ref } from "vue";
import { defineStore } from "pinia";
import * as api from "@/api/trash";
import type { TrashBatch } from "@/api/trash";
import { useToastStore } from "@/stores/toast";

export const useTrashStore = defineStore("trash", () => {
  const batches = ref<TrashBatch[]>([]);
  const loading = ref(false);

  async function fetchTrash() {
    loading.value = true;
    try {
      batches.value = await api.listTrash();
    } catch (e) {
      useToastStore().show("Failed to load trash", "error");
      throw e;
    } finally {
      loading.value = false;
    }
  }

  async function restore(batchId: string) {
    try {
      await api.restoreBatch(batchId);
      batches.value = batches.value.filter((b) => b.batch_id !== batchId);
      useToastStore().show("Restored", "success");
    } catch (e) {
      useToastStore().show("Failed to restore", "error");
      throw e;
    }
  }

  async function purge(batchId: string) {
    try {
      await api.purgeBatch(batchId);
      batches.value = batches.value.filter((b) => b.batch_id !== batchId);
    } catch (e) {
      useToastStore().show("Failed to delete permanently", "error");
      throw e;
    }
  }

  async function emptyTrash() {
    const ids = batches.value.map((b) => b.batch_id);
    for (const id of ids) {
      await api.purgeBatch(id);
    }
    batches.value = [];
  }

  return { batches, loading, fetchTrash, restore, purge, emptyTrash };
});
