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

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

const wpClient = createWpFetchClient({
  endpoint: process.env.WORDPRESS_API_URL!,
  username: process.env.WORDPRESS_API_USERNAME,
  password: process.env.WORDPRESS_API_PASSWORD,
  baseTag: "wp",
  defaultRevalidate: REVALIDATE_TIME,
});

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

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

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

const resolveServiceHierarchySlug = (
  service: any,
  serviceById: Map<number, any>
): string | null => {
  if (!service?.slug) {
    return null;
  }

  const slugs: string[] = [];
  const visited = new Set<number>();
  let current: any = service;

  while (current?.slug) {
    slugs.unshift(current.slug);
    const parentId = Number(current?.parent || 0);

    if (!parentId) {
      break;
    }

    if (visited.has(parentId)) {
      break;
    }

    visited.add(parentId);
    current = serviceById.get(parentId);
  }

  return slugs.join("/");
};

const findServiceRouteSegmentsFromPermalink = (
  service: any,
  routePrefix: string
): string[] | null => {
  const permalinkPath = getPathFromPermalink(service?.link || service?.permalink || "");
  if (!permalinkPath) {
    return null;
  }

  const pathSegments = permalinkPath.split("/").filter(Boolean);
  const prefixSegments = normalizePath(routePrefix).split("/").filter(Boolean);

  if (!prefixSegments.length) {
    return pathSegments.length ? pathSegments : null;
  }

  for (let i = 0; i <= pathSegments.length - prefixSegments.length; i++) {
    const matchedPrefix = prefixSegments.every(
      (prefixSegment, prefixIndex) => pathSegments[i + prefixIndex] === prefixSegment
    );

    if (!matchedPrefix) {
      continue;
    }

    const serviceSegments = pathSegments.slice(i + prefixSegments.length);
    return serviceSegments.length ? serviceSegments : null;
  }

  return null;
};

export const getCachedUsers = async () => {
  const response = await wpClient.request<any>("wp/v2/users", {
    query: { per_page: 30, acf_format: "standard" },
    revalidate: 360,
    includePaging: true,
    tags: ["wp:users"],
  });

  if (Array.isArray(response)) {
    return response;
  }

  if (Array.isArray(response?.data)) {
    return response.data;
  }

  if (Array.isArray(response?.users)) {
    return response.users;
  }

  return [];
};

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

  return removePaging(menu);
};

export const getCachedPage = async (slug: string) => {
  return wpClient.request<any[]>("wp/v2/pages", {
    query: { slug },
    includePaging: true,
    tags: ["wp:pages", `wp:page:${slug}`],
  });
};

export const getCachedService = async (slug: string) => {
  return wpClient.request<any[]>("wp/v2/service", {
    query: { slug },
    includePaging: true,
    tags: ["wp:services", `wp:service:${slug}`],
  });
};

export const getCachedServiceLandingPage = async () => {
  const explicitPageId = Number(process.env.WORDPRESS_SERVICE_PAGE_ID || 0);
  const fallbackSlug = process.env.WORDPRESS_SERVICE_PAGE_SLUG || "services";

  const fetchPageById = async (pageId: number) => {
    const page = await wpClient.request<any>(`wp/v2/pages/${pageId}`, {
      tags: ["wp:pages", `wp:page:${pageId}`, "wp:page:service-landing"],
    });

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

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

  if (explicitPageId > 0) {
    try {
      return await fetchPageById(explicitPageId);
    } catch {
      // Fallback to settings or slug lookup.
    }
  }

  try {
    const settings = await wpClient.request<any>("wp/v2/settings", {
      tags: ["wp:settings", "wp:settings:service-page"],
    });

    const configuredSettingKey = process.env.WORDPRESS_SERVICE_PAGE_SETTING_KEY;
    const candidateKeys = [
      configuredSettingKey,
      "page_on_service",
      "service_page",
      "service_page_id",
    ].filter(Boolean) as string[];

    for (const key of candidateKeys) {
      const value = Number(settings?.[key] || 0);
      if (value > 0) {
        try {
          return await fetchPageById(value);
        } catch {
          break;
        }
      }
    }
  } catch {
    // Fallback to slug lookup.
  }

  const pageBySlug = await getCachedPage(fallbackSlug);
  return Array.isArray(pageBySlug) ? pageBySlug : [];
};

export const getRawService = async (slug: string) => {
  return wpClient.request<any[]>("wp/v2/service", {
    query: { slug },
    includePaging: true,
    revalidate: SERVICE_LOOKUP_REVALIDATE_TIME,
    tags: ["wp:services", `wp:service:${slug}`, "wp:services:lookup"],
  });
};

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

  if (!lastSegment) {
    return null;
  }

  const services = await getRawService(lastSegment);
  const candidates = Array.isArray(services) ? services : [];

  if (candidates.length === 0) {
    return null;
  }

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

  const permalinkMatch = candidates.find((service: any) => {
    const permalinkPath = getPathFromPermalink(service.link || service.permalink || "");
    return permalinkPath.endsWith(expectedPath);
  });

  if (permalinkMatch) {
    return permalinkMatch;
  }

  const allServicesResponse = await wpClient.request<any[]>("wp/v2/service", {
    query: { per_page: 100 },
    includePaging: true,
    revalidate: SERVICE_LOOKUP_REVALIDATE_TIME,
    tags: ["wp:services", "wp:services:lookup:all"],
  });
  const allServices = removePaging(allServicesResponse);
  const serviceById = new Map<number, any>(
    (Array.isArray(allServices) ? allServices : [])
      .filter((service: any) => service?.id)
      .map((service: any) => [Number(service.id), service])
  );

  const hierarchyMatch = candidates.find((service: any) => {
    const hierarchySlug = resolveServiceHierarchySlug(service, serviceById);
    return hierarchySlug === expectedPath;
  });

  return hierarchyMatch || null;
};

export const getServicePathPrefix = async (service: any) => {
  const permalinkPath = getPathFromPermalink(service?.link || service?.permalink || "");

  if (permalinkPath) {
    const pathSegments = permalinkPath.split("/").filter(Boolean);
    pathSegments.pop();
    return pathSegments.join("/");
  }

  if (!service?.slug) {
    return "";
  }

  const allServicesResponse = await wpClient.request<any[]>("wp/v2/service", {
    query: { per_page: 100 },
    includePaging: true,
    revalidate: SERVICE_LOOKUP_REVALIDATE_TIME,
    tags: ["wp:services", "wp:services:lookup:all"],
  });
  const allServices = removePaging(allServicesResponse);
  const serviceById = new Map<number, any>(
    (Array.isArray(allServices) ? allServices : [])
      .filter((entry: any) => entry?.id)
      .map((entry: any) => [Number(entry.id), entry])
  );

  const hierarchySlug = resolveServiceHierarchySlug(service, serviceById);

  if (!hierarchySlug) {
    return "";
  }

  const hierarchySegments = hierarchySlug.split("/").filter(Boolean);
  hierarchySegments.pop();
  return hierarchySegments.join("/");
};

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

export const getRawPost = async (slug: string, status: string[] = ["publish"]) => {
  return wpClient.request<any[]>("wp/v2/posts", {
    query: { slug, status },
    includePaging: true,
    useCache: false,
  });
};

export const getCachedStickyPosts = async (count: number = 3) => {
  const posts = await wpClient.request<any[]>("wp/v2/posts", {
    query: { sticky: true, per_page: count, status: "publish" },
    includePaging: true,
    tags: ["wp:posts", "wp:posts:sticky"],
  });

  return removePaging(posts);
};

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

export const getCachedLatestCaseStudy = async () => {
  try {
    const caseStudy = await wpClient.request<any[]>("wp/v2/case-study", {
      query: { per_page: 1 },
      includePaging: true,
      tags: ["wp:case-studies", "wp:case-studies:latest"],
    });

    return removePaging(caseStudy);
  } catch (error) {
    console.error("ERROR FETCHING CASE STUDY:", error);
    return [];
  }
};

export const getCachedProjects = async (perPage: number = 100) => {
  const projects = await wpClient.request<any[]>("wp/v2/project", {
    query: { per_page: perPage },
    includePaging: true,
    tags: ["wp:projects"],
  });

  return removePaging(projects);
};

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

  return removePaging(caseStudies);
};

export const getCachedCaseStudiesByIds = async (ids: number[]) => {
  if (!ids.length) {
    return [];
  }

  const caseStudies = await wpClient.request<any[]>("wp/v2/case-study", {
    query: { include: ids, per_page: ids.length, acf_format: "standard" },
    includePaging: true,
    tags: ["wp:case-studies", "wp:case-studies:ids"],
  });

  return removePaging(caseStudies);
};

export const getCachedProject = async (slug: string) => {
  return wpClient.request<any[]>("wp/v2/project", {
    query: { slug },
    includePaging: true,
    tags: ["wp:projects", `wp:project:${slug}`],
  });
};

export const getCachedProjectsByIds = async (ids: number[]) => {
  if (!ids.length) {
    return [];
  }

  const projects = await wpClient.request<any[]>("wp/v2/project", {
    query: { include: ids, per_page: ids.length, acf_format: "standard" },
    includePaging: true,
    tags: ["wp:projects", "wp:projects:ids"],
  });

  return removePaging(projects);
};

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

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

export const getCachedEvents = async () => {
  const events = await wpClient.request<any[]>("wp/v2/event", {
    includePaging: true,
    tags: ["wp:events"],
  });

  return removePaging(events);
};

export const getCachedPostsByIds = async (ids: number[]) => {
  const posts = await wpClient.request<any[]>("wp/v2/posts", {
    query: { include: ids },
    includePaging: true,
    tags: ["wp:posts", "wp:posts:ids"],
  });

  return removePaging(posts);
};

export const getCachedServicesByIds = async (ids: number[]) => {
  if (!ids.length) {
    return [];
  }

  const services = await wpClient.request<any[]>("wp/v2/service", {
    query: { include: ids, per_page: ids.length, acf_format: "standard" },
    includePaging: true,
    tags: ["wp:services", "wp:services:ids"],
  });

  return removePaging(services);
};

export const getCachedSitemap = async (perPage: number = 100) => {
  const pages = await wpClient.request<any[]>("wp/v2/sitemap", {
    tags: ["wp:sitemap"],
  });

  return removePaging(pages);
};

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

  return removePaging(pages);
};

export const getCachedAllServices = async (perPage: number = 100) => {
  const services = await wpClient.request<any[]>("wp/v2/service", {
    query: { per_page: perPage },
    includePaging: true,
    tags: ["wp:services", "wp:services:all"],
  });

  return removePaging(services);
};

export const getCachedServiceRouteParams = async (): Promise<{ pageSlug: string[] }[]> => {
  const services = await getCachedAllServices(100);
  const serviceList = Array.isArray(services) ? services : [];
  const serviceById = new Map<number, any>(
    serviceList
      .filter((service: any) => service?.id)
      .map((service: any) => [Number(service.id), service])
  );

  const uniquePaths = new Set<string>();

  serviceList.forEach((service: any) => {
    const permalinkSegments = findServiceRouteSegmentsFromPermalink(service, SERVICE_ROUTE_PREFIX);

    if (permalinkSegments?.length) {
      uniquePaths.add(permalinkSegments.join("/"));
      return;
    }

    const hierarchySlug = resolveServiceHierarchySlug(service, serviceById);
    if (hierarchySlug) {
      uniquePaths.add(hierarchySlug);
    }
  });

  return Array.from(uniquePaths)
    .filter(Boolean)
    .map((path) => ({
      pageSlug: path.split("/").filter(Boolean),
    }))
    .filter((entry) => entry.pageSlug.length > 0);
};

export const getCachedAllProjects = async (perPage: number = 100) => {
  const projects = await wpClient.request<any[]>("wp/v2/project", {
    query: { per_page: perPage },
    includePaging: true,
    tags: ["wp:projects", "wp:projects:all"],
  });

  return removePaging(projects);
};

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

  return removePaging(posts);
};

export const getCachedMedia = async (id: number) => {
  return wpClient.request<any>(`wp/v2/media/${id}`, {
    tags: ["wp:media", `wp:media:${id}`],
  });
};

export const getCachedMediaByIds = async (ids: number[]) => {
  const media = await wpClient.request<any[]>("wp/v2/media", {
    query: { include: ids },
    includePaging: true,
    tags: ["wp:media", "wp:media:ids"],
  });

  return removePaging(media);
};

export const getCachedUser = async (id: number) => {
  return wpClient.request<any>(`wp/v2/users/${id}`, {
    tags: ["wp:users", `wp:user:${id}`],
  });
};
