import { NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { blogPosts } from '@/shared/schema';
import { eq, and, desc } from 'drizzle-orm';

// Universal Site ID resolution
const SITE_ID = (process.env.RANKTRACTION_SITE_ID || process.env.SITE_ID || 'example.com').replace(/"/g, '');

export const dynamic = 'force-dynamic';

export async function GET() {
  try {
    const rows = await db
      .select({
        title: blogPosts.title,
        slug: blogPosts.slug,
      })
      .from(blogPosts)
      .where(
        and(
          eq(blogPosts.siteId, SITE_ID),
          eq(blogPosts.isActive, true)
        )
      )
      .orderBy(desc(blogPosts.publicationDate));

    return NextResponse.json({ posts: rows });
  } catch (error) {
    console.error('Failed to fetch blog posts:', error);
    return NextResponse.json({ error: 'Failed to fetch blog posts' }, { status: 500 });
  }
}
