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

export async function GET(request) {
  let connection;
  
  try {
    connection = await pool.getConnection();

    // Data query for frontend
    const dataQuery = `
      SELECT 
        id,
        title,
        description,
        thumbnail,
        video_id,
        url,
        published_at,
        view_count,
        duration
      FROM youtube_videos 
      WHERE is_active = 1 AND featured = 1
      ORDER BY published_at DESC, created_at DESC
      LIMIT 4
    `;
    
    const [videos] = await connection.execute(dataQuery);

    return NextResponse.json({
      success: true,
      data: videos
    });
  } catch (error) {
    console.error("GET /frontend/youtube-videos error:", error);
    return NextResponse.json(
      { 
        success: false,
        error: "Failed to fetch videos", 
        details: error.message 
      },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}