import { NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import type { ResultSetHeader } from 'mysql2';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';


// ---------- GET: Fetch partners with pagination and filters ----------
export async function GET(req) {
  try {
    const { searchParams } = new URL(req.url);
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '15');
    const search = searchParams.get('search') || '';
    const startDate = searchParams.get('startDate') || '';
    const endDate = searchParams.get('endDate') || '';

    const offset = (page - 1) * limit;
    let whereConditions = ` WHERE 1=1`;
    const params = [];

    if (search) {
      whereConditions += ` AND name LIKE ?`;
      params.push(`%${search}%`);
    }

    if (startDate) {
      whereConditions += ` AND created_at >= ?`;
      params.push(startDate);
    }

    if (endDate) {
      whereConditions += ` AND created_at <= ?`;
      params.push(endDate + ' 23:59:59');
    }

    const countQuery = `SELECT COUNT(*) as total FROM tbl_partners ${whereConditions}`;
    const [countResult] = await pool.query(countQuery, params);
    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / limit);

    const dataQuery = `
      SELECT * FROM tbl_partners 
      ${whereConditions} 
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
    `;
    const [rows] = await pool.query(dataQuery, [...params, limit, offset]);

    return NextResponse.json({
      success: true,
      data: rows,
      meta: {
        currentPage: page,
        itemsPerPage: limit,
        totalItems,
        totalPages,
      },
    });
  } catch (error) {
    console.error('Fetch error:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch partners', error: error.message },
      { status: 500 }
    );
  }
}