import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';

export async function GET(request) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const page = parseInt(searchParams.get('page')) || 1;
    const limit = parseInt(searchParams.get('limit')) || 6;
    const search = searchParams.get('search') || '';
    const offset = (page - 1) * limit;

    // Build query conditions
    let conditions = ['n.is_active = 1'];
    let params = [];
    
    if (search) {
      conditions.push('(n.title LIKE ? OR n.description LIKE ?)');
      params.push(`%${search}%`, `%${search}%`);
    }

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    // Get total count
    const [countResult] = await pool.query(
      `SELECT COUNT(*) as total FROM news n ${whereClause}`,
      params
    );
    const totalItems = countResult[0].total;

    // Get paginated news
    const [news] = await pool.query(`
      SELECT 
        n.id,
        n.title,
        n.slug,
        n.description,
        n.image,
        n.is_featured,
        n.likes,
        n.created_at,
        n.updated_at,
        a.full_name as author_name,
        a.slug as author_slug,
        a.profile_image as author_image
      FROM news n
      LEFT JOIN authors a ON n.author_id = a.id
      ${whereClause}
      ORDER BY n.is_featured DESC, n.created_at DESC
      LIMIT ? OFFSET ?
    `, [...params, limit, offset]);

    return NextResponse.json({
      success: true,
      data: news,
      pagination: {
        currentPage: page,
        totalPages: Math.ceil(totalItems / limit),
        totalItems,
        limit
      }
    });

  } catch (error) {
    console.error('Error fetching news:', error);
    return NextResponse.json(
      { success: false, error: 'Failed to fetch news' },
      { status: 500 }
    );
  }
}