import 'server-only';

const API_URL = process.env.INTERNAL_API_URL || 'http://127.0.0.1:3021';

export interface BlogPostSummary {
  id?: string;
  slug: string;
  sport: string;
  title: string;
  canonical_url?: string | null;
  meta_description?: string | null;
  excerpt?: string | null;
  content?: string;
  tags?: string[] | null;
  home_team?: string | null;
  away_team?: string | null;
  event_id?: string | null;
  game_date?: string | null;
  published_at?: string | null;
  updated_at?: string | null;
}

export interface BlogSportSummary {
  sport: string;
  count: number;
}

export async function fetchBlogPosts(options: {
  sport?: string;
  page?: number;
  limit?: number;
} = {}): Promise<BlogPostSummary[]> {
  const params = new URLSearchParams();
  if (options.sport) params.set('sport', options.sport);
  if (options.page) params.set('page', String(options.page));
  if (options.limit) params.set('limit', String(options.limit));

  try {
    const qs = params.toString();
    const res = await fetch(`${API_URL}/api/blog/posts${qs ? `?${qs}` : ''}`, {
      next: { revalidate: 300 },
    });
    if (!res.ok) return [];
    const data = await res.json();
    return Array.isArray(data.posts) ? data.posts : [];
  } catch {
    return [];
  }
}

export async function fetchBlogPost(slug: string): Promise<BlogPostSummary | null> {
  try {
    const res = await fetch(`${API_URL}/api/blog/posts/${slug}`, {
      next: { revalidate: 300 },
    });
    if (!res.ok) return null;
    return res.json();
  } catch {
    return null;
  }
}

export async function fetchRelatedBlogPosts(sport: string, slug: string, limit: number = 3): Promise<BlogPostSummary[]> {
  const posts = await fetchBlogPosts({ sport, limit: Math.max(limit + 3, 6) });
  return posts.filter((post) => post.slug !== slug).slice(0, limit);
}

export async function fetchBlogSports(): Promise<BlogSportSummary[]> {
  try {
    const res = await fetch(`${API_URL}/api/blog/sports`, { next: { revalidate: 3600 } });
    if (!res.ok) return [];
    const data = await res.json();
    return Array.isArray(data) ? data : [];
  } catch {
    return [];
  }
}
