// app/api/internal/blogs/route.js
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from 'mysql2';

export async function GET(request: NextRequest) {
  try {
    const slug = request.nextUrl.searchParams.get('slug');

    const [getblogs] = await pool.query<RowDataPacket[]>(`
      SELECT 
        b.id, 
        b.category_id, 
        b.title, 
        b.slug, 
        b.short_description, 
        b.image, 
        b.is_active, 
        b.created_at,
        b.user_id,
        a.full_name as author_name,
        a.slug as author_slug,
        a.profile_image as author_image
      FROM blogs b
      LEFT JOIN authors a ON b.author_id = a.id
      WHERE b.slug != ? AND b.is_active = 1
      ORDER BY b.created_at DESC 
      LIMIT 3
    `, [slug]);

    if (getblogs.length === 0) {
      return NextResponse.json({
        success: false,
        error: "No blogs found",
      }, { status: 404 });
    }

    // Format the response to include minimal author data
    const formattedBlogs = getblogs.map(blog => {
      const author = blog.author_name ? {
        name: blog.author_name,
        slug: blog.author_slug,
        image: blog.author_image
      } : null;

      // Remove author fields from blog object
      const {
        author_name, author_slug, author_image, ...blogData
      } = blog;

      return {
        ...blogData,
        author
      };
    });

    return NextResponse.json({
      success: true,
      data: formattedBlogs,
    }, { status: 200 });

  } catch (err) {
    console.error("❌ GET API Error:", err);
    return NextResponse.json({ 
      success: false, 
      error: "Failed to fetch blogs", 
      details: err.message 
    }, { status: 500 });
  }
}