// D:\Nextjs\latest-deployed-universitiespage-code\src\app\api\internal\news\[id]\route.ts

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;
  }>;
};

// GET - Fetch single news by ID
export async function GET(
  request: NextRequest,
  { params }: PageProps
) {
  try {
    const {id} = await params;

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

    const [news] = await pool.query<RowDataPacket[]>(
      `SELECT 
        n.id, 
        n.title, 
        n.slug, 
        n.author_id,
        n.description, 
        n.image, 
        n.is_featured,
        n.is_active, 
        n.enable_meta_tags, 
        n.user_id, 
        n.seo, 
        n.sm_question,
        n.sm_answer,
        n.likes,
        n.created_at, 
        n.updated_at,
        a.full_name AS author_name,
        a.slug AS author_slug,
        a.profile_image AS author_image,
        u.first_name AS user_name,
        u.email AS user_email
      FROM news n
      LEFT JOIN authors a ON n.author_id = a.id
      LEFT JOIN users u ON n.user_id = u.id
      WHERE n.id = ?`,
      [id]
    );

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

    const newsItem = news[0];

    // Parse JSON fields safely
    try {
      if (newsItem.seo && typeof newsItem.seo === 'string') {
        newsItem.seo = JSON.parse(newsItem.seo);
      }
    } catch {
      newsItem.seo = {};
    }

    try {
      if (newsItem.sm_question && typeof newsItem.sm_question === 'string') {
        newsItem.sm_question = JSON.parse(newsItem.sm_question);
      }
    } catch {
      newsItem.sm_question = [''];
    }

    try {
      if (newsItem.sm_answer && typeof newsItem.sm_answer === 'string') {
        newsItem.sm_answer = JSON.parse(newsItem.sm_answer);
      }
    } catch {
      newsItem.sm_answer = [''];
    }

    return NextResponse.json({
      success: true,
      data: newsItem
    });

  } catch (error: any) {
    console.error('❌ GET /api/internal/news/[id] error:', error);
    return NextResponse.json(
      {
        success: false,
        message: 'Failed to fetch news',
        error: process.env.NODE_ENV === 'development' ? error.message : 'Internal server error'
      },
      { status: 500 }
    );
  }
}

// PUT - Update news
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 }
      );
    }

    const body = await request.json();

    const {
      title,
      slug,
      author_id,
      description,
      image,
      is_featured,
      is_active,
      enable_meta_tags,
      seo,
      sm_question,
      sm_answer,
      likes,
      meta_title,
      meta_description,
      meta_keywords,
    } = body;

    await connection.beginTransaction();

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

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

    // Validation
    const errors = [];
    if (title !== undefined && !title?.trim()) errors.push('Title is required');
    if (slug !== undefined && !slug?.trim()) errors.push('Slug is required');

    if (errors.length > 0) {
      console.error('Validation failed:', { errors, body });
      return NextResponse.json(
        { success: false, message: 'Validation failed', errors },
        { status: 400 }
      );
    }

    // Check if author exists (if provided)
    if (author_id !== undefined && author_id !== null && author_id !== '') {
      const [authorExists] = await connection.execute<RowDataPacket[]>(
        'SELECT id FROM authors WHERE id = ? AND status = "active"',
        [author_id]
      );

      if (authorExists.length === 0) {
        return NextResponse.json(
          { success: false, message: 'Invalid or inactive author' },
          { status: 400 }
        );
      }
    }

    // Check if slug is unique (excluding current news)
    if (slug !== undefined) {
      const [existingSlug] = await connection.execute<RowDataPacket[]>(
        'SELECT id FROM news WHERE slug = ? AND id != ?',
        [slug.trim(), id]
      );

      if (existingSlug.length > 0) {
        return NextResponse.json(
          { success: false, message: 'Another news with this slug already exists' },
          { status: 400 }
        );
      }
    }

    // Prepare SEO data
    let seoData = {};
    if (seo) {
      try {
        seoData = typeof seo === 'string' ? JSON.parse(seo) : seo;
      } catch {
        seoData = {};
      }
    } else if (meta_title || meta_description || meta_keywords) {
      seoData = {
        meta_title: meta_title || '',
        meta_description: meta_description || '',
        meta_keywords: meta_keywords || ''
      };
    }

    // Build update fields dynamically
    const updateFields: string[] = [];
    const updateValues: any[] = [];

    if (title !== undefined) {
      updateFields.push('title = ?');
      updateValues.push(title.trim());
    }

    if (slug !== undefined) {
      updateFields.push('slug = ?');
      updateValues.push(slug.trim());
    }

    if (author_id !== undefined) {
      updateFields.push('author_id = ?');
      updateValues.push(author_id ? Number(author_id) : null);
    }

    if (description !== undefined) {
      updateFields.push('description = ?');
      updateValues.push(description?.trim() || null);
    }

    if (image !== undefined) {
      updateFields.push('image = ?');
      updateValues.push(image?.trim() || null);
    }

    if (is_featured !== undefined) {
      updateFields.push('is_featured = ?');
      updateValues.push(Boolean(is_featured));
    }

    if (is_active !== undefined) {
      updateFields.push('is_active = ?');
      updateValues.push(Boolean(is_active));
    }

    if (enable_meta_tags !== undefined) {
      updateFields.push('enable_meta_tags = ?');
      updateValues.push(Boolean(enable_meta_tags));
    }

    if (seo !== undefined || meta_title !== undefined || meta_description !== undefined || meta_keywords !== undefined) {
      updateFields.push('seo = ?');
      updateValues.push(JSON.stringify(seoData));
    }

    if (sm_question !== undefined) {
      updateFields.push('sm_question = ?');
      updateValues.push(
        sm_question ? 
          (typeof sm_question === 'string' ? sm_question : JSON.stringify(sm_question)) 
          : JSON.stringify([''])
      );
    }

    if (sm_answer !== undefined) {
      updateFields.push('sm_answer = ?');
      updateValues.push(
        sm_answer ? 
          (typeof sm_answer === 'string' ? sm_answer : JSON.stringify(sm_answer)) 
          : JSON.stringify([''])
      );
    }

    if (likes !== undefined) {
      updateFields.push('likes = ?');
      updateValues.push(Number(likes) || 0);
    }

    // Always update updated_at
    updateFields.push('updated_at = CURRENT_TIMESTAMP');

    if (updateFields.length === 0) {
      return NextResponse.json(
        { success: false, message: 'No fields to update' },
        { status: 400 }
      );
    }

    const query = `
      UPDATE news 
      SET ${updateFields.join(', ')} 
      WHERE id = ?
    `;

    const [result] = await connection.execute<ResultSetHeader>(
      query,
      [...updateValues, id]
    );

    if (result.affectedRows === 0) {
      throw new Error('No rows were updated');
    }

    // Retrieve the updated news data
    const [updatedNews] = await connection.execute<RowDataPacket[]>(
      `SELECT 
        n.*,
        a.full_name AS author_name,
        a.slug AS author_slug,
        a.profile_image AS author_image,
        u.first_name AS user_name
      FROM news n
      LEFT JOIN authors a ON n.author_id = a.id
      LEFT JOIN users u ON n.user_id = u.id
      WHERE n.id = ?`,
      [id]
    );

    // Parse JSON fields for response
    const responseNews = updatedNews[0];
    if (responseNews) {
      try {
        if (responseNews.seo && typeof responseNews.seo === 'string') {
          responseNews.seo = JSON.parse(responseNews.seo);
        }
      } catch {
        responseNews.seo = {};
      }

      try {
        if (responseNews.sm_question && typeof responseNews.sm_question === 'string') {
          responseNews.sm_question = JSON.parse(responseNews.sm_question);
        }
      } catch {
        responseNews.sm_question = [''];
      }

      try {
        if (responseNews.sm_answer && typeof responseNews.sm_answer === 'string') {
          responseNews.sm_answer = JSON.parse(responseNews.sm_answer);
        }
      } catch {
        responseNews.sm_answer = [''];
      }
    }

    // Log activity
    await connection.query(
      "INSERT INTO activity_logs (user_id, action) VALUES (?, ?)", 
      [decoded.id, `News "${responseNews?.title || newsExists[0].title}" updated by user ${decoded.name} (${decoded.email})`]
    );

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: 'News updated successfully',
      data: responseNews
    });

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

// DELETE - Delete news
export async function DELETE(
  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 }
      );
    }

    await connection.beginTransaction();

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

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

    // Delete news
    await connection.execute(
      'DELETE FROM news WHERE id = ?',
      [id]
    );

    // Log activity
    await connection.query(
      "INSERT INTO activity_logs (user_id, action) VALUES (?, ?)", 
      [decoded.id, `News "${newsExists[0].title}" deleted by user ${decoded.name} (${decoded.email})`]
    );

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: 'News deleted successfully'
    });

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