import { create } from "zustand";
import type { PageMeta } from "@/stores/editorStore";

interface PagesStore {
  pages: PageMeta[];
  isLoading: boolean;
  fetchPages: () => Promise<void>;
  deletePage: (name: string) => Promise<void>;
  unpublishPage: (name: string) => Promise<void>;
}

export const usePagesStore = create<PagesStore>((set, get) => ({
  pages: [],
  isLoading: false,

  fetchPages: async () => {
    set({ isLoading: true });
    try {
      const res = await fetch("/api/pages");
      const pages = await res.json();
      set({ pages });
    } finally {
      set({ isLoading: false });
    }
  },

  deletePage: async (name: string) => {
    await fetch(`/api/pages/${name}`, { method: "DELETE" });
    await get().fetchPages();
  },

  unpublishPage: async (name: string) => {
    // Fetch current source, re-save as draft only
    const res = await fetch(`/api/pages/${name}`);
    const data = await res.json();
    if (data.source) {
      await fetch(`/api/pages/${name}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ source: data.source, publish: false }),
      });
    }
    await get().fetchPages();
  },
}));
