// @ts-nocheck
import { db } from '@/lib/db';
import { blogPosts, categories } from '@/lib/db/schema';
import { desc, eq, and, sql } from 'drizzle-orm';

const SITE_ID = 'littleleague';
import { ArticleStub, AuthorInfoStub, CategoryWithCount } from './db-editor-stubs';

function normalizeHeroImage(heroImage: any): string | undefined {
  if (!heroImage) return undefined;
  // If it's a JSON object with a url property
  if (typeof heroImage === 'object' && heroImage.url) {
    return heroImage.url;
  }
  // If it's a plain string URL
  if (typeof heroImage === 'string') {
    return heroImage;
  }
  return undefined;
}

function mapPostToStub(post: any): ArticleStub {
  return {
    slug: post.slug,
    title: post.title,
    cardImage: normalizeHeroImage(post.heroImage),
    excerpt: post.snippetIntro || post.metaDescription || undefined,
    category: post.category,
    author: typeof post.author === 'object' ? post.author?.name : post.author || undefined,
    publishedAt: post.datePublished ? new Date(post.datePublished) : undefined,
    readingTime: post.readingTime || undefined,
  };
}

export async function getLatestArticles(count: number): Promise<ArticleStub[]> {
  try {
    const posts = await db.query.blogPosts.findMany({
      where: eq(blogPosts.siteId, SITE_ID),
      orderBy: [desc(blogPosts.datePublished)],
      limit: count,
    });
    return posts.map(mapPostToStub);
  } catch (error) {
    console.error('Error fetching latest articles:', error);
    return [];
  }
}

export async function getTrendingArticles(count: number): Promise<ArticleStub[]> {
  try {
    // Fallback to likesCount or latest if trending logic is absent
    const posts = await db.query.blogPosts.findMany({
      where: eq(blogPosts.siteId, SITE_ID),
      orderBy: [desc(blogPosts.likesCount), desc(blogPosts.datePublished)],
      limit: count,
    });
    return posts.map(mapPostToStub);
  } catch (error) {
    console.error('Error fetching trending articles:', error);
    return [];
  }
}

export async function getMostReadArticles(count: number): Promise<ArticleStub[]> {
  try {
    // Since we don't have views, use likesCount or date
    const posts = await db.query.blogPosts.findMany({
      where: eq(blogPosts.siteId, SITE_ID),
      orderBy: [desc(blogPosts.likesCount)],
      limit: count,
    });
    return posts.map(mapPostToStub);
  } catch (error) {
    console.error('Error fetching most read articles:', error);
    return [];
  }
}

export async function getFeaturedArticle(): Promise<ArticleStub | null> {
  try {
    const post = await db.query.blogPosts.findFirst({
      where: and(eq(blogPosts.featured, true), eq(blogPosts.siteId, SITE_ID)),
      orderBy: [desc(blogPosts.datePublished)],
    });
    return post ? mapPostToStub(post) : null;
  } catch (error) {
    console.error('Error fetching featured article:', error);
    return null;
  }
}

export async function getFeaturedArticles(count: number): Promise<ArticleStub[]> {
  try {
    const posts = await db.query.blogPosts.findMany({
      where: and(eq(blogPosts.featured, true), eq(blogPosts.siteId, SITE_ID)),
      orderBy: [desc(blogPosts.datePublished)],
      limit: count,
    });
    return posts.map(mapPostToStub);
  } catch (error) {
    console.error('Error fetching featured articles:', error);
    return [];
  }
}

export type Article = ArticleStub;

export async function getPrimaryAuthor(): Promise<string> {
  return 'Little League Editor';
}

export async function getAuthorInfo(authorName: string): Promise<any> {
  return {
    authorName: authorName,
    authorBio: 'Editor at Little League',
    authorRole: 'Editor',
    authorProfileUrl: '',
    authorAvatar: '',
    socialTwitter: '',
    socialInstagram: '',
    socialYoutube: '',
    socialLinkedin: '',
    socialWebsite: '',
  };
}

export async function getLatestAuthorData(): Promise<any> {
  return {
    authorName: 'Little League Editor',
    authorBio: 'Editor at Little League',
    authorProfileUrl: '',
    authorAvatar: '',
    authorRole: 'Editor',
    socialTwitter: '',
    socialInstagram: '',
    socialYoutube: '',
    socialLinkedin: '',
    socialWebsite: '',
  };
}

export async function getAllCategoriesWithCount(): Promise<CategoryWithCount[]> {
  try {
    // Rough count for now
    const allCats = await db.query.categories.findMany();
    return allCats.map(c => ({
      name: c.name,
      count: 0 // Ideally this would join with blogPosts
    }));
  } catch (error) {
    console.error('Error fetching categories:', error);
    return [];
  }
}

export async function getCategoryArticles(categoryName: string, limit: number): Promise<ArticleStub[]> {
  try {
    const posts = await db.query.blogPosts.findMany({
      where: and(eq(blogPosts.category, categoryName), eq(blogPosts.siteId, SITE_ID)),
      orderBy: [desc(blogPosts.datePublished)],
      limit,
    });
    return posts.map(mapPostToStub);
  } catch (error) {
    console.error('Error fetching category articles:', error);
    return [];
  }
}
