/**
 * Tickets Data API Endpoint
 * GET /api/data/tickets - Query tickets 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: create_date)
 * - order: Sort order ASC/DESC (default: DESC)
 * - companyId: Filter by company ID
 * - status: Filter by status
 * - assignedResourceId: Filter by assigned resource
 * - 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 {
    const searchParams = request.nextUrl.searchParams;
    const ids = searchParams.get('ids'); // Comma-separated IDs for enrichment
    
    // Handle ID-based enrichment requests
    if (ids) {
      const idArray = ids.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
      if (idArray.length === 0) {
        return NextResponse.json({ tickets: [] });
      }
      
      const query = `
        SELECT id, ticket_number, title, status, priority, company_id
        FROM tickets
        WHERE id = ANY($1) AND is_deleted = false
      `;
      
      const result = await postgresClient.query(query, [idArray]);
      return NextResponse.json({ tickets: result.rows });
    }
    
    // Parse and validate query parameters
    const options = parseQueryParams(request, {
      limit: 100,
      sort: 'create_date',
      order: 'DESC',
    });

    validateQueryParams(options);

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

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

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

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

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

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