import { createClient } from "@sanity/client";

export const client = createClient({
  projectId: import.meta.env.PUBLIC_SANITY_PROJECT_ID ?? "placeholder",
  dataset: import.meta.env.PUBLIC_SANITY_DATASET ?? "production",
  apiVersion: "2024-01-01",
  useCdn: true,
});

// Bildurl aus Sanity-Asset
export function imageUrl(asset: any, width = 800): string {
  if (!asset?.asset?._ref) return "";
  const [, id, dimensions, format] = asset.asset._ref.split("-");
  return `https://cdn.sanity.io/images/${import.meta.env.PUBLIC_SANITY_PROJECT_ID}/production/${id}-${dimensions}.${format}?w=${width}&auto=format`;
}

// --- Queries ---

export async function getSettings() {
  try {
    return await client.fetch(`*[_type == "siteSettings"][0]{
      contact, bank, social, memberFees, stats
    }`);
  } catch { return null; }
}

export async function getFeaturedProjects() {
  try {
    return await client.fetch(`*[_type == "project" && featured == true] | order(_createdAt desc)[0..5]{
      title, slug, date, summary, status,
      image{ asset->{ url } }
    }`);
  } catch { return []; }
}

export async function getAllProjects() {
  try {
    return await client.fetch(`*[_type == "project"] | order(_createdAt desc){
      title, slug, date, summary, status, targetGroup,
      image{ asset->{ url } }
    }`);
  } catch { return []; }
}

export async function getProject(slug: string) {
  try {
    return await client.fetch(`*[_type == "project" && slug.current == $slug][0]{
      title, slug, date, summary, body, status, targetGroup,
      image{ asset->{ url } }
    }`, { slug });
  } catch { return null; }
}

export async function getLatestPosts(limit = 6) {
  try {
    return await client.fetch(`*[_type == "post"] | order(publishedAt desc)[0..${limit - 1}]{
      title, slug, publishedAt, excerpt, category,
      coverImage{ asset->{ url } }
    }`);
  } catch { return []; }
}

export async function getAllPosts() {
  try {
    return await client.fetch(`*[_type == "post"] | order(publishedAt desc){
      title, slug, publishedAt, excerpt, category,
      coverImage{ asset->{ url } }
    }`);
  } catch { return []; }
}

export async function getPost(slug: string) {
  try {
    return await client.fetch(`*[_type == "post" && slug.current == $slug][0]{
      title, slug, publishedAt, excerpt, body, category,
      coverImage{ asset->{ url } }
    }`, { slug });
  } catch { return null; }
}

export async function getTeam() {
  try {
    return await client.fetch(`*[_type == "teamMember"] | order(order asc){
      name, role, bio,
      photo{ asset->{ url } }
    }`);
  } catch { return []; }
}
