import { groq } from "next-sanity";
import { client } from "../sanity";

export interface blogPost {
  title: string;
  headline: string;
  currentSlug: string;
  postImage: any;
  content: any;
  dateCreated: Date;
  featured: boolean;
}

export async function getBlogPosts() {
  const query = groq`
        *[_type == 'blog'] | order(_createdAt desc) {
        title,
            headline,
            "currentSlug":slug.current,
            "postImage": image.asset._ref,
            content,
            "dateCreated": _createdAt,
            featured
        } 
    `;

  const data: blogPost[] = await client.fetch(query, {}, { cache: "no-cache" });

  return data;
}

export async function getBlogPostBySlug(slug: string) {
  const query = `
        *[_type=="blog" && slug.current == '${slug}']{
        title,
            headline,
            "currentSlug": slug.current,
            "postImage": image.asset._ref,
            content,
            "dateCreated": _createdAt,
            featured
            
        }[0]
    `;
  const data: blogPost = await client.fetch(query, {}, { cache: "no-cache" });
  return data;
}

export async function getFeaturedBlogPost() {
  const query = `
       *[_type=="blog" && featured==true] {
        title,
        headline,
        "currentSlug": slug.current,
        "postImage": image.asset._ref,
        content,
        "dateCreated": _createdAt,
        featured 
        } 
    `;
  const data: blogPost[] = await client.fetch(query, {}, { cache: "no-cache" });
  return data;
}