/**
 * Configuration Items Data API Endpoint
 * GET /api/data/configuration-items - Query configuration items 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');

    // Build where clause
    const where: Record<string, any> = {};
    if (companyId) {
      where.company_id = parseInt(companyId);
    }
    if (isActive !== null) {
      where.is_active = isActive === 'true';
    }

    // Query configuration items
    const configurationItems = await postgresClient.find(
      'configuration_items',
      where,
      {
        limit,
        offset,
        orderBy: 'reference_title ASC',
      }
    );

    // Get total count
    const totalCount = await postgresClient.count('configuration_items', where);

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