const DIRECTUS_URL = import.meta.env.DIRECTUS_URL ?? "https://cms.kitafreunde-regenbogen.de";
const DIRECTUS_TOKEN = import.meta.env.DIRECTUS_TOKEN ?? "";

async function fetchDirectus<T>(path: string): Promise<T | null> {
  try {
    const res = await fetch(`${DIRECTUS_URL}${path}`, {
      headers: DIRECTUS_TOKEN ? { Authorization: `Bearer ${DIRECTUS_TOKEN}` } : {},
    });
    if (!res.ok) return null;
    const json = await res.json();
    return json.data ?? null;
  } catch {
    return null;
  }
}

export function imageUrl(fileId: string | null | undefined, width = 800): string {
  if (!fileId) return "";
  return `${DIRECTUS_URL}/assets/${fileId}?width=${width}&format=webp`;
}

export async function getSettings() {
  return fetchDirectus<{
    contact_email: string; contact_phone: string;
    iban: string; bic: string; bank_name: string;
    member_fee_active: number; member_fee_supporting: number; member_fee_company: number;
    stats_members: number; stats_funded: number;
    social_instagram: string; social_facebook: string;
  }>("/items/site_settings");
}

export async function getFeaturedProjects() {
  const data = await fetchDirectus<any[]>(
    "/items/projects?filter[featured][_eq]=true&filter[status][_neq]=archived&sort=-date&limit=6"
  );
  return data ?? [];
}

export async function getAllProjects() {
  const data = await fetchDirectus<any[]>(
    "/items/projects?filter[status][_neq]=archived&sort[]=sort&sort[]=-date"
  );
  return data ?? [];
}

export async function getProject(slug: string) {
  const data = await fetchDirectus<any[]>(
    `/items/projects?filter[slug][_eq]=${encodeURIComponent(slug)}&limit=1`
  );
  return data?.[0] ?? null;
}

export async function getLatestPosts(limit = 6) {
  const data = await fetchDirectus<any[]>(
    `/items/posts?filter[status][_eq]=published&sort=-published_at&limit=${limit}`
  );
  return data ?? [];
}

export async function getAllPosts() {
  const data = await fetchDirectus<any[]>(
    "/items/posts?filter[status][_eq]=published&sort=-published_at"
  );
  return data ?? [];
}

export async function getPost(slug: string) {
  const data = await fetchDirectus<any[]>(
    `/items/posts?filter[slug][_eq]=${encodeURIComponent(slug)}&limit=1`
  );
  return data?.[0] ?? null;
}

export async function getTeam() {
  const data = await fetchDirectus<any[]>(
    "/items/team_members?sort[]=sort&sort[]=name"
  );
  return data ?? [];
}
