import { createClient, type SanityDocument } from "@sanity/client";
import imageUrlBuilder from "@sanity/image-url"
import type { SanityImageSource } from "@sanity/image-url/lib/types/types";

const sanityClientConfig = {
  dataset: "production",
  projectId: "qpfygham",
  useCdn: true,
  apiVersion: "2024-06-01"
};

const client = createClient(sanityClientConfig);

export async function getRecentBlogPosts(limit: number = 3) {
  const query = `*[_type == "blog-post"]|order(publishedDate desc)[0...${limit}]{
    _id,
    title,
    content, 
    slug,
    publishedDate,
    image, 
    tags[]->{
      _id,
      title
    }
  }`;

  return client.fetch<SanityDocument[]>(query);
}

export async function getBlogPostBySlug(slug: string) {
  const query = `*[_type == "blog-post" && slug.current == "${slug}"][0]{
    _id,
    title,
    content,
    slug,
    publishedDate,
    author,
    image,
    tags[]->{
      _id,
      title
    }
  }`;

  return await client.fetch<SanityDocument>(query);
}

export async function getProjectItems(limit: number = 3) {
  const query = `*[_type == "project"]|order(publishedDate desc)[0...${limit}]{
    _id,
    title,
    description,
    slug,
    startDate,
    endDate,
    category -> {
      title
    },
    bannerImage,
    tags[]->{
      _id,
      title
    }
  }`;

  return client.fetch<SanityDocument[]>(query);
}

export async function getProjectBySlug(slug: string) {
    const query = `*[_type == "project" && slug.current == "${slug}"][0]{
    _id,
    title,
    description,
    slug,
    startDate,
    endDate,
    client,
    results,
    category -> {
      title
    },
    bannerImage,
    tags[]->{
      _id,
      title
    },
    images
  }`;

  return client.fetch<SanityDocument>(query);
}

export async function getTestimonials(limit: number = 10) {
  const query = `*[_type == "testimonial"]|order(_createdAt desc)[0...${limit}]{
    _id,
    name,
    organisation, 
    comment
  }`;

  return client.fetch<SanityDocument[]>(query);
}

export async function getFrequentlyAskedQuestions(limit: number = 10) {
  const query = `*[_type == "frequentlyAskedQuestion"]|order(_createdAt desc)[0...${limit}]{
    _id,
    question,
    answer
  }`;

  return client.fetch<SanityDocument[]>(query);
}

export const getUrlForImage = (source: SanityImageSource) => sanityClientConfig.projectId && sanityClientConfig.dataset
    ? imageUrlBuilder({ projectId: sanityClientConfig.projectId, dataset: sanityClientConfig.dataset }).image(source)
    : null;

export { client as SanityClient };
