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

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

    if (!slug) {
      return NextResponse.json(
        { success: false, error: 'Slug is required' },
        { status: 400 }
      );
    }

    const [news] = await pool.query(`
      SELECT 
        n.*,
        a.full_name as author_name,
        a.slug as author_slug,
        a.profile_image as author_image,
        a.bio as author_bio,
        a.full_name as author_title,
        a.website as author_website,
        a.social_facebook,
        a.social_twitter,
        a.social_instagram,
        a.social_linkedin
      FROM news n
      LEFT JOIN authors a ON n.author_id = a.id
      WHERE n.slug = ? AND n.is_active = 1
    `, [slug]);

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

    // Format author data
    const newsData = news[0];
    const author = newsData.author_name ? {
      full_name: newsData.author_name,
      slug: newsData.author_slug,
      profile_image: newsData.author_image,
      bio: newsData.author_bio,
      title: newsData.author_title,
      website: newsData.author_website,
      social_facebook: newsData.social_facebook,
      social_twitter: newsData.social_twitter,
      social_instagram: newsData.social_instagram,
      social_linkedin: newsData.social_linkedin
    } : null;

    // Remove author fields from news object
    const {
      author_name, author_slug, author_image, author_bio, author_title,
      author_website, social_facebook, social_twitter, social_instagram,
      social_linkedin, ...cleanNewsData
    } = newsData;

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

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