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


export async function GET(request) {

    const connection = await pool.getConnection();

  try {
    const { searchParams } = new URL(request.url);
    const page = parseInt(searchParams.get('page')) || 1;
    const limit = parseInt(searchParams.get('limit')) || 15;
    const search = searchParams.get('search');
    const startDate = searchParams.get('start_date');
    const endDate = searchParams.get('end_date');

    const offset = (page - 1) * limit;

    // Build WHERE conditions
    let whereConditions = [];
    let queryParams = [];

    if (search) {
      whereConditions.push('(al.action LIKE ? OR u.email LIKE ?)');
      const searchTerm = `%${search}%`;
      queryParams.push(searchTerm, searchTerm);
    }

    if (startDate) {
      whereConditions.push('DATE(al.created_at) >= ?');
      queryParams.push(startDate);
    }

    if (endDate) {
      whereConditions.push('DATE(al.created_at) <= ?');
      queryParams.push(endDate);
    }

    const whereClause = whereConditions.length > 0 
      ? `WHERE ${whereConditions.join(' AND ')}` 
      : '';

    // Count query for pagination
    const countQuery = `
      SELECT COUNT(*) as total
      FROM activity_logs al
      LEFT JOIN users u ON al.user_id = u.id
      ${whereClause}
    `;

    // Main data query
    const dataQuery = `
      SELECT 
        al.id,
        al.action,
        al.created_at,
        al.user_id,
        u.email as user_email
      FROM activity_logs al
      LEFT JOIN users u ON al.user_id = u.id
      ${whereClause}
      ORDER BY al.created_at DESC
      LIMIT ? OFFSET ?
    `;

    // Add limit and offset to query params
    const dataQueryParams = [...queryParams, limit, offset];

    // Execute queries
    const [countResult] = await connection.execute(countQuery, queryParams);
    const [logs] = await connection.execute(dataQuery, dataQueryParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / limit);

    return NextResponse.json({
      success: true,
      logs,
      meta: {
        currentPage: page,
        itemsPerPage: limit,
        totalItems,
        totalPages,
        hasNextPage: page < totalPages,
        hasPrevPage: page > 1
      }
    });

  } catch (error) {
    console.error('Activity logs fetch error:', error);
    return NextResponse.json(
      { 
        success: false, 
        error: 'Failed to fetch activity logs',
        message: error.message 
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}