import { create } from "zustand";
import * as api from "@/api/client";

interface PagesStore {
  pages: api.PageMeta[];
  isLoading: boolean;
  fetchPages: () => Promise<void>;
  deletePage: (name: string) => Promise<void>;
  publishPage: (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 pages = await api.fetchPages();
      set({ pages });
    } finally {
      set({ isLoading: false });
    }
  },

  deletePage: async (name: string) => {
    await api.deletePage(name);
    await get().fetchPages();
  },

  publishPage: async (name: string) => {
    const page = await api.fetchPage(name);
    if (page.source) {
      await api.savePage(name, page.source, true);
    }
    await get().fetchPages();
  },

  unpublishPage: async (name: string) => {
    const page = await api.fetchPage(name);
    if (page.source) {
      await api.savePage(name, page.source, false);
    }
    await get().fetchPages();
  },
}));
