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

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { slug } = body;

    // Modified query to join with authors table
    const [results] = await pool.query<RowDataPacket[]>(`
      SELECT 
        b.*,
        a.id as author_id,
        a.full_name as author_name,
        a.slug as author_slug,
        a.profile_image as author_image,
        a.bio as author_bio,
        a.website as author_website,
        a.social_facebook as author_facebook,
        a.social_twitter as author_twitter,
        a.social_instagram as author_instagram,
        a.social_linkedin as author_linkedin,
        a.created_at as author_created_at
      FROM blogs b
      LEFT JOIN authors a ON b.author_id = a.id
      WHERE b.slug = ? AND b.is_active = 1
    `, [slug]);

    if (results.length === 0) {
      return NextResponse.json({
        success: false,
        error: "Blog not found",
      }, { status: 404 });
    }

    // Format author data
    const blogData = results[0];
    const authorData = blogData.author_id ? {
      id: blogData.author_id,
      full_name: blogData.author_name,
      slug: blogData.author_slug,
      profile_image: blogData.author_image,
      bio: blogData.author_bio,
      website: blogData.author_website,
      social_facebook: blogData.author_facebook,
      social_twitter: blogData.author_twitter,
      social_instagram: blogData.author_instagram,
      social_linkedin: blogData.author_linkedin,
      created_at: blogData.author_created_at
    } : null;

    // Remove author fields from blog data
    const {
      author_id, author_name, author_slug, author_image, author_bio,
      author_website, author_facebook, author_twitter, author_instagram,
      author_linkedin, author_created_at,
      ...cleanBlogData
    } = blogData;

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

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