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

type PageProps = {
  params: Promise<{
    id: string;
  }>;
};

export async function PUT(
  request: NextRequest,
  { params }: PageProps
) {
  const connection = await pool.getConnection();

  const token = request.cookies.get("university-token")?.value || null;
  
  if (!token) {
    return NextResponse.json(
      {
        message: "Please Login to continue"
      },
      {
        status: 401
      }
    );
  }

  const decoded = await verifyAuthentication(token);

  if (decoded instanceof NextResponse) {
    return NextResponse.json(
      {
        message: "You are not authorized to do this action"
      },
      {
        status: 403
      }
    );
  }

  try {
    const {id} = await params;

    if (!id || isNaN(parseInt(id))) {
      return NextResponse.json(
        { success: false, message: 'Valid news ID is required' },
        { status: 400 }
      );
    }

    // Get the current featured status from request body
    const body = await request.json();
    const { is_featured } = body;

    if (is_featured === undefined) {
      return NextResponse.json(
        { success: false, message: 'is_featured field is required' },
        { status: 400 }
      );
    }

    await connection.beginTransaction();

    // Check if news exists
    const [newsExists] = await connection.execute<RowDataPacket[]>(
      'SELECT id, title, is_featured FROM news WHERE id = ?',
      [id]
    );

    if (newsExists.length === 0) {
      return NextResponse.json(
        { success: false, message: 'News not found' },
        { status: 404 }
      );
    }

    const currentNews = newsExists[0];
    const newStatus = Boolean(is_featured);

    // Update the featured status
    await connection.execute<ResultSetHeader>(
      'UPDATE news SET is_featured = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
      [newStatus, id]
    );

    // Retrieve the updated news data
    const [updatedNews] = await connection.execute<RowDataPacket[]>(
      `SELECT 
        n.id, 
        n.title, 
        n.slug,
        n.is_featured,
        n.is_active,
        n.author_id,
        a.full_name AS author_name
      FROM news n
      LEFT JOIN authors a ON n.author_id = a.id
      WHERE n.id = ?`,
      [id]
    );

    // Log activity
    await connection.query(
      "INSERT INTO activity_logs (user_id, action) VALUES (?, ?)", 
      [
        decoded.id, 
        `News "${currentNews.title}" featured status changed to ${newStatus ? 'Featured' : 'Not Featured'} by user ${decoded.name} (${decoded.email})`
      ]
    );

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: `News marked as ${newStatus ? 'Featured' : 'Not Featured'} successfully`,
      data: updatedNews[0]
    });

  } catch (error: any) {
    console.error('❌ PUT /api/internal/news/toggleFeatured/[id] error:', error);
    await connection.rollback();
    return NextResponse.json(
      {
        success: false,
        message: 'Failed to update featured status',
        error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}