import { defineStore, storeToRefs } from "pinia";
import { usePageStore } from "./page";

export const useBriefStore = defineStore("brief", () => {
  async function addPdf(event, briefUri, redirectToParent = false) {
    const file = event.target.files[0];
    const { page } = storeToRefs(usePageStore());

    if (file) {
      const formData = new FormData();
      formData.append("file", file);

      try {
        const response = await fetch("/upload-pdf.json?pageUri=" + briefUri, {
          method: "POST",
          body: formData,
        });

        const result = await response.json();

        if (response.ok) {
          page.value.steps[0].files.push(result);
        } else {
          console.error("Error uploading file:", result.error);
        }
      } catch (error) {
        console.error("Request failed:", error);
      }
    } else {
      console.error("No file selected.");
    }
  }

  return { addPdf };
});
