/**
 * Issue Types Data API Endpoint
 * GET /api/data/issue-types - Query issue types 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 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 (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 sort_order ASC, label ASC';
    if (sortBy) {
      const validColumns = ['value', 'label', 'is_active', 'is_system', 'sort_order', 'parent_value'];
      if (validColumns.includes(sortBy)) {
        const direction = sortOrder.toLowerCase() === 'desc' ? 'DESC' : 'ASC';
        orderByClause = `ORDER BY ${sortBy} ${direction}, sort_order ASC, label ASC`;
      }
    }

    // Query issue types
    const query = `
      SELECT 
        value,
        label,
        is_active,
        is_system,
        sort_order,
        parent_value,
        created_at,
        updated_at,
        synced_at,
        is_deleted,
        deleted_at
      FROM issue_types
      ${whereClause}
      ${orderByClause}
      LIMIT $${params.length + 1} OFFSET $${params.length + 2}
    `;

    params.push(limit, offset);

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

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

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

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