/**
 * Enhanced Sub-Issue Types Data API Endpoint with Parent Issue Type Assignment
 * GET /api/data/sub-issue-types-with-parent - Query sub-issue types with assigned parent issue type labels
 */

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');

    // 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 ') : '';

    // 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,
        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}
      ORDER BY sit.parent_value ASC, sit.sort_order ASC, sit.label ASC
      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 with parent:', error);
    return NextResponse.json(
      { error: 'Failed to fetch sub-issue types with parent' },
      { status: 500 }
    );
  }
}
