import { jsx } from 'react/jsx-runtime';
import { lazy } from 'react';
import { defineClientPlugin, createApiClient } from '@btst/stack/plugins/client';
import { createRoute } from '@btst/yar';
import { createCMSQueryKeys } from '../../../../../../plugins/cms/query-keys.mjs';

const DashboardPageComponent = lazy(
  () => import('./components/pages/dashboard-page.mjs').then((m) => ({
    default: m.DashboardPageComponent
  }))
);
const ContentListPageComponent = lazy(
  () => import('./components/pages/content-list-page.mjs').then((m) => ({
    default: m.ContentListPageComponent
  }))
);
const ContentEditorPageComponent = lazy(
  () => import('./components/pages/content-editor-page.mjs').then((m) => ({
    default: m.ContentEditorPageComponent
  }))
);
function createDashboardLoader(config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const context = {
        path: "/cms",
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadDashboard) {
          const canLoad = await hooks.beforeLoadDashboard(context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadDashboard hook");
          }
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createCMSQueryKeys(client, headers);
        await queryClient.prefetchQuery(queries.cmsTypes.list());
        if (hooks?.afterLoadDashboard) {
          await hooks.afterLoadDashboard(context);
        }
        const queryState = queryClient.getQueryState(
          queries.cmsTypes.list().queryKey
        );
        if (queryState?.error && hooks?.onLoadError) {
          const error = queryState.error instanceof Error ? queryState.error : new Error(String(queryState.error));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createContentListLoader(typeSlug, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const context = {
        path: `/cms/${typeSlug}`,
        params: { typeSlug },
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadContentList) {
          const canLoad = await hooks.beforeLoadContentList(typeSlug, context);
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadContentList hook");
          }
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createCMSQueryKeys(client, headers);
        const limit = 20;
        await queryClient.prefetchQuery(queries.cmsTypes.list());
        const listQuery = queries.cmsContent.list({
          typeSlug,
          limit,
          offset: 0
        });
        await queryClient.prefetchInfiniteQuery({
          queryKey: listQuery.queryKey,
          queryFn: async ({ pageParam = 0 }) => {
            const response = await client("/content/:typeSlug", {
              method: "GET",
              params: { typeSlug },
              query: { limit, offset: pageParam },
              headers
            });
            if (typeof response === "object" && response !== null && "error" in response && response.error) {
              throw new Error(String(response.error));
            }
            return response.data;
          },
          initialPageParam: 0
        });
        if (hooks?.afterLoadContentList) {
          await hooks.afterLoadContentList(typeSlug, context);
        }
        const typesState = queryClient.getQueryState(
          queries.cmsTypes.list().queryKey
        );
        const listState = queryClient.getQueryState(listQuery.queryKey);
        const queryError = typesState?.error || listState?.error;
        if (queryError && hooks?.onLoadError) {
          const error = queryError instanceof Error ? queryError : new Error(String(queryError));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createContentEditorLoader(typeSlug, id, config) {
  return async () => {
    if (typeof window === "undefined") {
      const { queryClient, apiBasePath, apiBaseURL, headers, hooks } = config;
      const context = {
        path: id ? `/cms/${typeSlug}/${id}` : `/cms/${typeSlug}/new`,
        params: id ? { typeSlug, id } : { typeSlug },
        isSSR: true,
        apiBaseURL,
        apiBasePath,
        headers
      };
      try {
        if (hooks?.beforeLoadContentEditor) {
          const canLoad = await hooks.beforeLoadContentEditor(
            typeSlug,
            id,
            context
          );
          if (!canLoad) {
            throw new Error("Load prevented by beforeLoadContentEditor hook");
          }
        }
        const client = createApiClient({
          baseURL: apiBaseURL,
          basePath: apiBasePath
        });
        const queries = createCMSQueryKeys(client, headers);
        const promises = [queryClient.prefetchQuery(queries.cmsTypes.list())];
        if (id) {
          promises.push(
            queryClient.prefetchQuery(queries.cmsContent.detail(typeSlug, id))
          );
        }
        await Promise.all(promises);
        if (hooks?.afterLoadContentEditor) {
          await hooks.afterLoadContentEditor(typeSlug, id, context);
        }
        const typesState = queryClient.getQueryState(
          queries.cmsTypes.list().queryKey
        );
        const itemState = id ? queryClient.getQueryState(
          queries.cmsContent.detail(typeSlug, id).queryKey
        ) : null;
        const queryError = typesState?.error || itemState?.error;
        if (queryError && hooks?.onLoadError) {
          const error = queryError instanceof Error ? queryError : new Error(String(queryError));
          await hooks.onLoadError(error, context);
        }
      } catch (error) {
        if (hooks?.onLoadError) {
          await hooks.onLoadError(error, context);
        }
      }
    }
  };
}
function createDashboardMeta() {
  return () => {
    const title = "CMS Dashboard";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
function createContentListMeta(typeSlug, config) {
  return () => {
    const { queryClient, apiBasePath, apiBaseURL } = config;
    const client = createApiClient({
      baseURL: apiBaseURL,
      basePath: apiBasePath
    });
    const queries = createCMSQueryKeys(client);
    const contentTypes = queryClient.getQueryData(
      queries.cmsTypes.list().queryKey
    );
    const contentType = contentTypes?.find((ct) => ct.slug === typeSlug);
    const title = contentType?.name ? `${contentType.name} | CMS` : "Content | CMS";
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
function createContentEditorMeta(typeSlug, id, config) {
  return () => {
    const { queryClient, apiBasePath, apiBaseURL } = config;
    const client = createApiClient({
      baseURL: apiBaseURL,
      basePath: apiBasePath
    });
    const queries = createCMSQueryKeys(client);
    const contentTypes = queryClient.getQueryData(
      queries.cmsTypes.list().queryKey
    );
    const contentType = contentTypes?.find((ct) => ct.slug === typeSlug);
    const title = id ? `Edit ${contentType?.name || "Content"} | CMS` : `New ${contentType?.name || "Content"} | CMS`;
    return [
      { title },
      { name: "title", content: title },
      { name: "robots", content: "noindex" }
    ];
  };
}
const cmsClientPlugin = (config) => defineClientPlugin({
  name: "cms",
  routes: () => ({
    dashboard: createRoute("/cms", () => ({
      PageComponent: () => /* @__PURE__ */ jsx(DashboardPageComponent, {}),
      loader: createDashboardLoader(config),
      meta: createDashboardMeta()
    })),
    contentList: createRoute("/cms/:typeSlug", ({ params }) => ({
      PageComponent: () => /* @__PURE__ */ jsx(ContentListPageComponent, { typeSlug: params.typeSlug }),
      loader: createContentListLoader(params.typeSlug, config),
      meta: createContentListMeta(params.typeSlug, config)
    })),
    newContent: createRoute("/cms/:typeSlug/new", ({ params }) => ({
      PageComponent: () => /* @__PURE__ */ jsx(ContentEditorPageComponent, { typeSlug: params.typeSlug }),
      loader: createContentEditorLoader(params.typeSlug, void 0, config),
      meta: createContentEditorMeta(params.typeSlug, void 0, config)
    })),
    editContent: createRoute("/cms/:typeSlug/:id", ({ params }) => ({
      PageComponent: () => /* @__PURE__ */ jsx(
        ContentEditorPageComponent,
        {
          typeSlug: params.typeSlug,
          id: params.id
        }
      ),
      loader: createContentEditorLoader(params.typeSlug, params.id, config),
      meta: createContentEditorMeta(params.typeSlug, params.id, config)
    }))
  }),
  sitemap: async () => {
    return [];
  }
});

export { cmsClientPlugin };
