import { api, hasApiConfigured } from "@/lib/api";
import type { IProject } from "@/types";
import { queryKeys } from "@/queries/keys";
import { queryOptions, useQuery } from "@tanstack/react-query";

/** Тег фильтра на стороне API (как в CMS). */
export const REMOTE_DEMO_TAG = "Удаленная демонстрация";

function releaseTimestamp(p: IProject): number {
  const t = Date.parse(p.releaseDate);
  return Number.isNaN(t) ? 0 : t;
}

export function useGetProjectsQuery(tags?: string | string[]) {
  const tagList =
    tags && tags.length > 0
      ? Array.isArray(tags)
        ? tags
        : [tags]
      : [];

  return useQuery(
    queryOptions({
      queryKey: queryKeys.projectsWithTags(tagList),
      queryFn: () => {
        if (tagList.length === 0) {
          return api.get("projects").json<IProject[]>();
        }
        const qs = tagList
          .map((tag) => `tags=${encodeURIComponent(tag)}`)
          .join("&");
        return api.get(`projects?${qs}`).json<IProject[]>();
      },
      enabled: hasApiConfigured,
      select:
        tags === REMOTE_DEMO_TAG ||
        (Array.isArray(tags) &&
          tags.length === 1 &&
          tags[0] === REMOTE_DEMO_TAG)
          ? (data) =>
              [...data]
                .sort((a, b) => releaseTimestamp(b) - releaseTimestamp(a))
                .slice(0, 3)
          : undefined,
    })
  );
}
