/**
 * Contacts Data API Endpoint
 * GET /api/data/contacts - Query contacts from PostgreSQL
 */

import { NextRequest, NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';

export async function GET(request: NextRequest) {
  try {
    const searchParams = request.nextUrl.searchParams;
    const limit = parseInt(searchParams.get('limit') || '100');
    const offset = parseInt(searchParams.get('offset') || '0');
    const companyId = searchParams.get('companyId');
    const isActive = searchParams.get('isActive');
    const sortBy = searchParams.get('sort');
    const sortOrder = searchParams.get('order') || 'asc';

    // Build conditions and parameters
    const conditions: string[] = [];
    const params: any[] = [];

    if (companyId) {
      conditions.push('company_id = $' + (params.length + 1));
      params.push(parseInt(companyId));
    }
    if (isActive !== null) {
      conditions.push('is_active = $' + (params.length + 1));
      params.push(isActive === 'true');
    }

    const whereClause = conditions.length > 0 ? 'WHERE ' + conditions.join(' AND ') : '';

    // Build dynamic ORDER BY clause
    let orderByClause = 'ORDER BY last_name ASC, first_name ASC';
    if (sortBy) {
      const validColumns = ['id', 'first_name', 'last_name', 'email_address', 'title', 'is_active', 'company_id'];
      if (validColumns.includes(sortBy)) {
        const direction = sortOrder.toLowerCase() === 'desc' ? 'DESC' : 'ASC';
        orderByClause = `ORDER BY ${sortBy} ${direction}, last_name ASC, first_name ASC`;
      }
    }

    // Query contacts
    const query = `
      SELECT 
        id,
        first_name,
        last_name,
        email_address,
        title,
        phone,
        extension,
        alternate_phone,
        mobile_phone,
        fax,
        address_line,
        address_line1,
        city,
        state,
        zip_code,
        country,
        is_active,
        company_id,
        created_at,
        updated_at,
        synced_at,
        is_deleted,
        deleted_at
      FROM contacts
      ${whereClause}
      ${orderByClause}
      LIMIT $${params.length + 1} OFFSET $${params.length + 2}
    `;

    params.push(limit, offset);

    const result = await postgresClient.query(query, params);
    const contacts = result.rows;

    // Get total count
    const countQuery = `
      SELECT COUNT(*) as total
      FROM contacts
      ${whereClause}
    `;

    const countResult = await postgresClient.query(countQuery, params.slice(0, -2));
    const totalCount = parseInt(countResult.rows[0].total);

    return NextResponse.json({
      contacts,
      pagination: {
        limit,
        offset,
        total: totalCount,
        hasMore: offset + contacts.length < totalCount,
      },
    });
  } catch (error) {
    console.error('Failed to fetch contacts:', error);
    return NextResponse.json(
      { error: 'Failed to fetch contacts' },
      { status: 500 }
    );
  }
}
