import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';

export async function GET(request: NextRequest) {
  const { searchParams } = request.nextUrl;
  const page = Math.max(1, parseInt(searchParams.get('page') || '1'));
  const limit = Math.min(50, Math.max(1, parseInt(searchParams.get('limit') || '20')));
  const sport = searchParams.get('sport');
  const type = searchParams.get('type');
  const offset = (page - 1) * limit;

  const conditions: string[] = ["status = 'published'"];
  const params: (string | number)[] = [];
  let paramIdx = 1;

  if (sport) {
    conditions.push(`sport = $${paramIdx++}`);
    params.push(sport);
  }
  if (type) {
    conditions.push(`content_type = $${paramIdx++}`);
    params.push(type);
  }

  const where = conditions.join(' AND ');

  try {
    const [postsResult, countResult] = await Promise.all([
      query(
        `SELECT id, slug, title, meta_description, excerpt, sport, content_type, league, game_date, featured_image, published_at, page_views
         FROM sc_blog_posts
         WHERE ${where}
         ORDER BY published_at DESC
         LIMIT $${paramIdx} OFFSET $${paramIdx + 1}`,
        [...params, limit, offset]
      ),
      query(
        `SELECT COUNT(*) as total FROM sc_blog_posts WHERE ${where}`,
        params
      ),
    ]);

    const total = parseInt(countResult.rows[0]?.total || '0');

    const res = NextResponse.json({
      posts: postsResult.rows,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
    res.headers.set('Access-Control-Allow-Origin', 'https://sportsclaw.guru');
    res.headers.set('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=60');
    return res;
  } catch (error) {
    console.error('[blog api] List error:', error);
    return NextResponse.json({ error: 'Failed to fetch posts' }, { status: 500 });
  }
}
