/**
 * Companies Data API Endpoint
 * GET /api/data/companies - Query companies from PostgreSQL
 * 
 * Query Parameters:
 * - page: Page number (default: 1)
 * - limit: Records per page (default: 100, max: 1000)
 * - includeDeleted: Include soft-deleted records (default: false)
 * - sort: Sort field (default: company_name)
 * - order: Sort order ASC/DESC (default: ASC)
 * - isActive: Filter by active status (true/false)
 * - Any other parameter will be treated as a filter
 */

import { NextRequest, NextResponse } from 'next/server';
import postgresClient from '@/lib/services/postgres-client';
import {
  parseQueryParams,
  buildWhereClause,
  buildOrderByClause,
  createPaginationInfo,
  formatApiResponse,
  handleApiError,
  validateQueryParams,
} from '@/lib/utils/api-helpers';

export async function GET(request: NextRequest) {
  try {
    // Parse and validate query parameters
    const options = parseQueryParams(request, {
      limit: 100,
      sort: 'company_name',
      order: 'ASC',
    });

    validateQueryParams(options);

    // Build WHERE clause
    const where = buildWhereClause(options.filters || {}, options.includeDeleted);

    // Build ORDER BY clause
    const orderBy = buildOrderByClause(options.sort!, options.order!);

    // Query companies
    const companies = await postgresClient.find(
      'companies',
      where,
      {
        limit: options.limit,
        offset: options.offset,
        orderBy,
        includeDeleted: options.includeDeleted,
      }
    );

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

    // Create pagination info
    const pagination = createPaginationInfo(options.page!, options.limit!, totalCount);

    // Format and return response
    return NextResponse.json(
      formatApiResponse(companies, pagination, {
        entity: 'companies',
        filters: options.filters,
      })
    );
  } catch (error) {
    const errorResponse = handleApiError(error, 'fetch companies');
    return NextResponse.json(errorResponse, { status: errorResponse.statusCode });
  }
}
