import { NextResponse } from 'next/server';
import db from '@/lib/db';

// GET /api/publish/article-data/[productId]
// Check publish status and get article data for a product
export async function GET(
  request: Request,
  { params }: { params: Promise<{ productId: string }> }
) {
  try {
    const { productId } = await params;

    if (!productId) {
      return NextResponse.json({ error: 'Product ID is required' }, { status: 400 });
    }

    // Get product data
    const productRows = await db.query(
      `SELECT p.*, c.name as categoryName, c.slug as categorySlug
       FROM Product p
       JOIN Category c ON p.categoryId = c.id
       WHERE p.id = ?`,
      [productId]
    );

    if (!Array.isArray(productRows) || productRows.length === 0) {
      return NextResponse.json({ error: 'Product not found' }, { status: 404 });
    }

    const product = productRows[0];

    // Get article content
    const articleRows = await db.query(
      `SELECT * FROM ProductArticle WHERE productId = ?`,
      [productId]
    );

    let articleContent = product.productDescription || '';
    let richTextState = null;

    if (Array.isArray(articleRows) && articleRows.length > 0) {
      articleContent = articleRows[0].productDescription || articleContent;
      if (articleRows[0].richTextState) {
        try {
          richTextState = JSON.parse(articleRows[0].richTextState);
        } catch (e) {
          // Keep as string
        }
      }
    }

    // Get publish history
    const publishHistory = await db.query(
      `SELECT * FROM published_articles WHERE product_id = ? ORDER BY published_at DESC`,
      [productId]
    );

    return NextResponse.json({
      success: true,
      product: {
        id: product.id,
        name: product.name,
        slug: product.slug,
        description: product.description,
        price: product.price,
        image: product.image,
        brand: product.brand,
        badge: product.badge,
        categoryName: product.categoryName,
        categorySlug: product.categorySlug,
        publishStatus: product.publishStatus,
        faqs: product.faqs ? (() => {
          try { return JSON.parse(product.faqs); } catch { return []; }
        })() : [],
      },
      article: {
        content: articleContent,
        richTextState,
      },
      publishHistory: Array.isArray(publishHistory) ? publishHistory : [],
    });
  } catch (error: any) {
    console.error('[Publish] Article data fetch failed:', error);
    return NextResponse.json(
      { error: error.message || 'Failed to fetch article data' },
      { status: 500 }
    );
  }
}
