import { createServerFn } from "@tanstack/react-start";
import { createClient } from "@supabase/supabase-js";
import type { Database } from "@/integrations/supabase/types";

export const BLOG_CATEGORIES = [
  "AI Automation",
  "Mobile Apps",
  "Blockchain",
  "Social Impact",
] as const;

export interface BlogPostSummary {
  id: string;
  slug: string;
  title: string;
  category: string;
  excerpt: string;
  author: string;
  published_at: string | null;
}

export interface BlogPost extends BlogPostSummary {
  content: string;
  cover_image: string | null;
}

function publicClient() {
  const key = process.env.SUPABASE_PUBLISHABLE_KEY!;
  return createClient<Database>(process.env.SUPABASE_URL!, key, {
    auth: { persistSession: false, autoRefreshToken: false },
    global: {
      fetch: (input, init) => {
        const h = new Headers(init?.headers);
        if (key.startsWith("sb_") && h.get("Authorization") === `Bearer ${key}`) {
          h.delete("Authorization");
        }
        h.set("apikey", key);
        return fetch(input, { ...init, headers: h });
      },
    },
  });
}

export const listPosts = createServerFn({ method: "GET" }).handler(async () => {
  const { data, error } = await publicClient()
    .from("blog_posts")
    .select("id, slug, title, category, excerpt, author, published_at")
    .eq("published", true)
    .order("published_at", { ascending: false });

  if (error) {
    console.error("listPosts failed", error);
    return [] as BlogPostSummary[];
  }
  return (data ?? []) as BlogPostSummary[];
});

export const getPost = createServerFn({ method: "GET" })
  .inputValidator((slug: string) => String(slug).slice(0, 200))
  .handler(async ({ data: slug }) => {
    const { data, error } = await publicClient()
      .from("blog_posts")
      .select("id, slug, title, category, excerpt, author, published_at, content, cover_image")
      .eq("slug", slug)
      .eq("published", true)
      .maybeSingle();

    if (error) {
      console.error("getPost failed", error);
      return null;
    }
    return (data as BlogPost | null) ?? null;
  });
