import { createWpFetchClient } from "@/services/wp-fetch";

const REVALIDATE_TIME = parseInt(
  process.env.PS_CACHE_REVALIDATE_TIME || process.env.CACHE_REVALIDATE_TIME || "3600",
  10
);

const psWpClient = createWpFetchClient({
  endpoint: process.env.PS_WORDPRESS_API_URL!,
  username: process.env.PS_WORDPRESS_API_USERNAME,
  password: process.env.PS_WORDPRESS_API_PASSWORD,
  baseTag: "ps-wp",
  defaultRevalidate: REVALIDATE_TIME,
});

const normalizePath = (path: string) => path.replace(/^\/+|\/+$/g, "");

const getPathFromPermalink = (permalink: string) => {
  try {
    const url = new URL(permalink);
    return normalizePath(url.pathname);
  } catch {
    return normalizePath(permalink);
  }
};

const removePaging = <T>(data: T): T => {
  if (data && typeof data === "object" && "_paging" in (data as object)) {
    delete (data as { _paging?: unknown })._paging;
  }
  return data;
};

export const getCachedPSPosts = async (page: number = 1, perPage: number = 10) => {
  const data = await psWpClient.request<any>("wp/v2/posts", {
    query: { status: "publish", per_page: perPage, page },
    includePaging: true,
    tags: ["ps-wp:posts", `ps-wp:posts:page:${page}:${perPage}`],
  });

  return {
    posts: data,
    _paging: data?._paging,
  };
};

export const getCachedPSPost = async (slug: string, status: string[] = ["publish"]) => {
  return psWpClient.request<any[]>("wp/v2/posts", {
    query: { slug, status },
    includePaging: true,
    tags: ["ps-wp:posts", `ps-wp:post:${slug}`],
  });
};

export const getCachedPSServices = async (perPage: number = 100) => {
  const services = await psWpClient.request<any[]>("wp/v2/development-services", {
    query: {
      status: "publish",
      per_page: perPage,
      orderby: "menu_order",
      order: "asc",
    },
    includePaging: true,
    tags: ["ps-wp:services", "ps-wp:services:all"],
  });

  return removePaging(services);
};

export const getCachedPSService = async (slug: string, status: string[] = ["publish"]) => {
  return psWpClient.request<any[]>("wp/v2/development-services", {
    query: { slug, status },
    includePaging: true,
    tags: ["ps-wp:services", `ps-wp:service:${slug}`],
  });
};

export const getCachedPSMenu = async () => {
  const menu = await psWpClient.request<any>("wp/v2/main_menu", {
    revalidate: 60,
    includePaging: true,
    tags: ["ps-wp:menu"],
  });

  return removePaging(menu);
};

export const getCachedPSAllPosts = async (
  perPage: number = 100,
  status: string[] = ["publish"]
) => {
  const posts = await psWpClient.request<any[]>("wp/v2/posts", {
    query: { status, per_page: perPage },
    includePaging: true,
    tags: ["ps-wp:posts", "ps-wp:posts:all"],
  });

  return removePaging(posts);
};

export const getCachedPSCaseStudies = async (perPage: number = 15) => {
  const caseStudies = await psWpClient.request<any[]>("wp/v2/case-study", {
    query: { per_page: perPage },
    includePaging: true,
    tags: ["ps-wp:case-studies"],
  });

  return removePaging(caseStudies);
};

export const getCachedPSCaseStudy = async (slug: string) => {
  return psWpClient.request<any[]>("wp/v2/case-study", {
    query: { slug },
    includePaging: true,
    tags: ["ps-wp:case-studies", `ps-wp:case-study:${slug}`],
  });
};

export const getCachedPSChildServices = async (parentId: number, perPage: number = 100) => {
  if (!parentId) {
    return [];
  }

  const services = await psWpClient.request<any[]>("wp/v2/development-services", {
    query: {
      parent: parentId,
      status: "publish",
      per_page: perPage,
      orderby: "menu_order",
      order: "asc",
    },
    includePaging: true,
    tags: ["ps-wp:services", `ps-wp:services:parent:${parentId}`],
  });

  const normalizedServices = removePaging(services);
  return Array.isArray(normalizedServices) ? normalizedServices : [];
};

export const getCachedPSAllPages = async (perPage: number = 100) => {
  const pages = await psWpClient.request<any[]>("wp/v2/pages", {
    query: { status: "publish", per_page: perPage },
    includePaging: true,
    tags: ["ps-wp:pages", "ps-wp:pages:all"],
  });

  return removePaging(pages);
};

export const getCachedPSFrontPage = async () => {
  const settings = await psWpClient.request<any>("wp/v2/settings", {
    tags: ["ps-wp:settings"],
  });

  if (settings?.show_on_front !== "page") {
    return [];
  }

  const frontPageId = Number(settings?.page_on_front || 0);
  if (!frontPageId) {
    return [];
  }

  const page = await psWpClient.request<any>(`wp/v2/pages/${frontPageId}`, {
    query: { status: "publish" },
    tags: ["ps-wp:pages", `ps-wp:page:${frontPageId}`],
  });

  if (page && !Array.isArray(page)) {
    return [page];
  }

  return Array.isArray(page) ? page : [];
};

export const getCachedPSPageByPath = async (pathSegments: string[]) => {
  const segments = pathSegments.filter(Boolean);
  const lastSegment = segments[segments.length - 1];

  if (!lastSegment) {
    return [];
  }

  const pages = await psWpClient.request<any[]>("wp/v2/pages", {
    query: { slug: lastSegment, status: "publish" },
    includePaging: true,
    tags: ["ps-wp:pages", `ps-wp:path:${segments.join("/")}`],
  });

  const expectedPath = normalizePath(segments.join("/"));

  return pages.filter((page: any) => {
    const pagePath = getPathFromPermalink(page.link || page.permalink || "");
    return pagePath.endsWith(expectedPath);
  });
};
