import { mergeQueryKeys, createQueryKeys } from '@lukemorales/query-key-factory';
import { postsListDiscriminator } from '../../packages/stack/src/plugins/blog/api/query-key-defs.mjs';

function isErrorResponse(response) {
  return typeof response === "object" && response !== null && "error" in response && response.error !== null && response.error !== void 0;
}
function toError(error) {
  if (error instanceof Error) {
    return error;
  }
  if (typeof error === "object" && error !== null) {
    const errorObj = error;
    const message = (typeof errorObj.message === "string" ? errorObj.message : null) || (typeof errorObj.error === "string" ? errorObj.error : null) || JSON.stringify(error);
    const err = new Error(message);
    Object.assign(err, error);
    return err;
  }
  return new Error(String(error));
}
function createBlogQueryKeys(client, headers) {
  const posts = createPostsQueries(client, headers);
  const drafts = createDraftsQueries(client, headers);
  const tags = createTagsQueries(client, headers);
  return mergeQueryKeys(posts, drafts, tags);
}
function createPostsQueries(client, headers) {
  return createQueryKeys("posts", {
    list: (params) => ({
      queryKey: [
        postsListDiscriminator({
          published: params?.published ?? true,
          limit: params?.limit ?? 10,
          tagSlug: params?.tagSlug,
          query: params?.query
        })
      ],
      queryFn: async ({ pageParam }) => {
        try {
          const response = await client("/posts", {
            method: "GET",
            query: {
              query: params?.query,
              offset: pageParam ?? 0,
              limit: params?.limit ?? 10,
              published: params?.published !== void 0 ? params.published ? "true" : "false" : void 0,
              tagSlug: params?.tagSlug
            },
            headers
          });
          if (isErrorResponse(response)) {
            const errorResponse = response;
            throw toError(errorResponse.error);
          }
          const dataResponse = response;
          return dataResponse.data?.items ?? [];
        } catch (error) {
          throw error;
        }
      }
    }),
    // Simplified detail query
    detail: (slug) => ({
      queryKey: [slug],
      queryFn: async () => {
        if (!slug) return null;
        try {
          const response = await client("/posts", {
            method: "GET",
            query: { slug, limit: 1 },
            headers
          });
          if (isErrorResponse(response)) {
            const errorResponse = response;
            throw toError(errorResponse.error);
          }
          const dataResponse = response;
          return dataResponse.data?.items?.[0] ?? null;
        } catch (error) {
          throw error;
        }
      }
    }),
    // Next/previous posts query
    nextPrevious: (date) => ({
      queryKey: ["nextPrevious", date],
      queryFn: async () => {
        const dateValue = typeof date === "string" ? new Date(date) : date;
        const response = await client("/posts/next-previous", {
          method: "GET",
          query: {
            date: dateValue.toISOString()
          },
          headers
        });
        if (isErrorResponse(response)) {
          const errorResponse = response;
          throw toError(errorResponse.error);
        }
        const dataResponse = response;
        return dataResponse.data;
      }
    }),
    // Recent posts query (separate from main list to avoid cache conflicts)
    recent: (params) => ({
      queryKey: ["recent", params],
      queryFn: async () => {
        try {
          const response = await client("/posts", {
            method: "GET",
            query: {
              limit: params?.limit ?? 5,
              published: "true"
            },
            headers
          });
          if (isErrorResponse(response)) {
            const errorResponse = response;
            throw toError(errorResponse.error);
          }
          const recentResponse = response;
          let posts = recentResponse.data?.items ?? [];
          if (params?.excludeSlug) {
            posts = posts.filter((post) => post.slug !== params.excludeSlug);
          }
          return posts;
        } catch (error) {
          throw error;
        }
      }
    })
  });
}
function createDraftsQueries(client, headers) {
  return createQueryKeys("drafts", {
    list: (params) => ({
      queryKey: [
        {
          ...params?.limit && { limit: params.limit }
        }
      ],
      queryFn: async ({ pageParam }) => {
        try {
          const response = await client("/posts", {
            method: "GET",
            query: {
              query: params?.query,
              offset: pageParam ?? 0,
              limit: params?.limit ?? 10,
              published: "false"
            },
            headers
          });
          if (isErrorResponse(response)) {
            const errorResponse = response;
            throw toError(errorResponse.error);
          }
          const draftsResponse = response;
          return draftsResponse.data?.items ?? [];
        } catch (error) {
          throw error;
        }
      }
    })
  });
}
function createTagsQueries(client, headers) {
  return createQueryKeys("tags", {
    list: () => ({
      queryKey: ["tags"],
      queryFn: async () => {
        try {
          const response = await client("/tags", {
            method: "GET",
            headers
          });
          if (isErrorResponse(response)) {
            const errorResponse = response;
            throw toError(errorResponse.error);
          }
          return response.data ?? [];
        } catch (error) {
          throw error;
        }
      }
    })
  });
}

export { createBlogQueryKeys };
