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

export async function GET(req: NextRequest) {
    const connection = await pool.getConnection();

    const comingHeaders = req.headers.get("authorization");

    if(comingHeaders !== process.env.APP_API_KEY) {
        return NextResponse.json(
            { success: false, message: 'Unauthorized Access' },
            { status: 401 }
        );
    }

    try {
        const [blogs] = await connection.query<RowDataPacket[]>(`
            SELECT 
                id, 
                title, 
                slug, 
                image, 
                created_at 
            FROM blogs 
            WHERE is_active = 1 AND is_featured = 1 
            ORDER BY created_at DESC 
            LIMIT 8
        `);

        if(blogs.length === 0) {
            return NextResponse.json({
                success: false,
                message: 'No popular blogs found',
                data: []
            });
        }

        return NextResponse.json({
            success: true,
            data: blogs
        });

    } catch (error) {
        console.error('Database error fetching popular blogs:', error);
        return NextResponse.json({
            success: false,
            message: error instanceof Error ? error.message : 'Unknown error occurred',
            data: []
        }, { status: 500 });
    } finally {
        connection.release();
    }
}