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

// GET - Fetch comments for a scholarship
export async function GET(request) {

    const connection = await pool.getConnection();

  try {
    const { searchParams } = new URL(request.url);
    const scholarshipId = searchParams.get('scholarship_id');

    if (!scholarshipId) {
      return NextResponse.json({ error: 'Scholarship ID is required' }, { status: 400 });
    }

    // Get approved comments and their replies
    const [comments] = await connection.query<RowDataPacket[]>(
      `SELECT 
        c.*,
        COUNT(r.id) as reply_count
       FROM scholarships_comments c
       LEFT JOIN scholarships_comments r ON c.id = r.parent_id AND r.is_approved = TRUE
       WHERE c.scholarship_id = ? AND c.is_approved = TRUE AND c.parent_id IS NULL
       GROUP BY c.id
       ORDER BY c.created_at DESC`,
      [scholarshipId]
    );

    // Get replies for each comment
    for (let comment of comments) {
      const [replies] = await connection.execute(
        `SELECT * FROM scholarships_comments 
         WHERE parent_id = ? AND is_approved = TRUE 
         ORDER BY created_at ASC`,
        [comment.id]
      );
      comment.replies = replies;
    }

    return NextResponse.json({ comments });
  } catch (error) {
    console.error('Error fetching comments:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}

// POST - Create a new comment or reply
export async function POST(request) {


    const connection = await pool.getConnection();

  try {
    const body = await request.json();
    const { scholarship_id, parent_id, first_name, last_name, email, phone, comment } = body;

    // Validation
    if (!scholarship_id || !first_name || !last_name || !email || !comment) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const [result] = await connection.query<ResultSetHeader>(
      `INSERT INTO scholarships_comments 
       (scholarship_id, parent_id, first_name, last_name, email, phone, comment) 
       VALUES (?, ?, ?, ?, ?, ?, ?)`,
      [scholarship_id, parent_id || null, first_name, last_name, email, phone, comment]
    );

    return NextResponse.json({ 
      message: 'Comment submitted successfully. It will be visible after approval.',
      comment_id: result.insertId 
    }, { status: 201 });

  } catch (error) {
    console.error('Error creating comment:', error);
    return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
  } finally {
    if (connection) {
      connection.release();
    }
  }
}