import { NextResponse } from 'next/server'
import mysql from 'mysql2/promise'

export const dynamic = 'force-dynamic'

async function getPool() {
  return mysql.createPool({
    host: 'localhost',
    user: 'sitemente',
    password: 'pa0ndoQRPDYBHzTXX3rbWd6E',
    database: 'sitemente',
    waitForConnections: true,
    connectionLimit: 10
  })
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url)
  const segment = searchParams.get('segment')
  const dormancy = searchParams.get('dormancy')
  const search = searchParams.get('search')
  const sortBy = searchParams.get('sortBy') || 'total_spent'
  const sortOrder = searchParams.get('sortOrder') || 'DESC'
  const page = parseInt(searchParams.get('page') || '1')
  const limit = parseInt(searchParams.get('limit') || '100')
  const offset = (page - 1) * limit
  
  // Validate sortBy to prevent SQL injection
  const allowedSortColumns = ['firstname', 'lastname', 'email', 'company', 'country', 'total_spent', 'segment', 'dormancy_flag', 'id']
  const safeSortBy = allowedSortColumns.includes(sortBy) ? sortBy : 'total_spent'
  const safeSortOrder = sortOrder === 'ASC' ? 'ASC' : 'DESC'
  
  try {
    const pool = await getPool()
    
    let countQuery = 'SELECT COUNT(*) as total FROM hostpioneers_leads WHERE 1=1'
    let query = 'SELECT * FROM hostpioneers_leads WHERE 1=1'
    const params: any[] = []
    
    if (segment && segment !== 'all') {
      countQuery += ' AND segment = ?'
      query += ' AND segment = ?'
      params.push(segment)
    }
    if (dormancy && dormancy !== 'all') {
      countQuery += ' AND dormancy_flag = ?'
      query += ' AND dormancy_flag = ?'
      params.push(dormancy)
    }
    if (search) {
      const searchClause = ' AND (firstname LIKE ? OR lastname LIKE ? OR email LIKE ? OR company LIKE ? OR phone LIKE ? OR country LIKE ?)'
      countQuery += searchClause
      query += searchClause
      const searchTerm = `%${search}%`
      params.push(searchTerm, searchTerm, searchTerm, searchTerm, searchTerm, searchTerm)
    }
    
    const [countResult] = await pool.query(countQuery, params)
    const total = (countResult as any[])[0].total
    
    query += ` ORDER BY ${safeSortBy} ${safeSortOrder} LIMIT ? OFFSET ?`
    const [rows] = await pool.query(query, [...params, limit, offset])
    
    await pool.end()
    
    return NextResponse.json({ 
      leads: rows,
      pagination: { page, limit, total, totalPages: Math.ceil(total / limit) }
    })
  } catch (error) {
    console.error('Error:', error)
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 })
  }
}
