/**
 * Sub-Issue Types Data API Endpoint
 * GET /api/data/sub-issue-types - Query sub-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 parentValue = searchParams.get('parentValue');
    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('sit.is_active = $' + (params.length + 1));
      params.push(isActive === 'true');
    }
    if (parentValue) {
      conditions.push('sit.parent_value = $' + (params.length + 1));
      params.push(parseInt(parentValue));
    }

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

    // Build dynamic ORDER BY clause
    let orderByClause = 'ORDER BY sit.parent_value ASC, sit.sort_order ASC, sit.label ASC';
    if (sortBy) {
      const validColumns = ['value', 'label', 'is_active', 'is_system', 'sort_order', 'parent_value', 'parent_issue_type_label'];
      if (validColumns.includes(sortBy)) {
        const direction = sortOrder.toLowerCase() === 'desc' ? 'DESC' : 'ASC';
        if (sortBy === 'parent_issue_type_label') {
          orderByClause = `ORDER BY it.label ${direction}, sit.sort_order ASC, sit.label ASC`;
        } else {
          orderByClause = `ORDER BY sit.${sortBy} ${direction}, sit.sort_order ASC, sit.label ASC`;
        }
      }
    }
    
    // Query sub-issue types with parent issue type information
    const query = `
      SELECT 
        sit.value,
        sit.label,
        sit.is_active,
        sit.is_system,
        sit.sort_order,
        sit.parent_value,
        sit.created_at,
        sit.updated_at,
        sit.synced_at,
        sit.is_deleted,
        sit.deleted_at,
        it.label as parent_issue_type_label,
        it.is_active as parent_is_active
      FROM sub_issue_types sit
      LEFT JOIN issue_types it ON sit.parent_value = it.value
      ${whereClause}
      ${orderByClause}
      LIMIT $${params.length + 1} OFFSET $${params.length + 2}
    `;

    params.push(limit, offset);

    // Execute query
    const result = await postgresClient.query(query, params);
    const subIssueTypes = result.rows;

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

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

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