/**
 * Enhanced Tickets Data API Endpoint with Issue Type Assignment
 * GET /api/data/tickets-with-issue-types - Query tickets with assigned issue type and sub-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 status = searchParams.get('status');
    const priority = searchParams.get('priority');
    const companyId = searchParams.get('companyId');
    const issueType = searchParams.get('issueType');
    const subIssueType = searchParams.get('subIssueType');

    // Build where clause
    const conditions: string[] = [];
    const params: any[] = [];
    let paramIndex = 1;

    if (status !== null) {
      conditions.push(`t.status = $${paramIndex++}`);
      params.push(parseInt(status));
    }
    if (priority !== null) {
      conditions.push(`t.priority = $${paramIndex++}`);
      params.push(parseInt(priority));
    }
    if (companyId !== null) {
      conditions.push(`t.company_id = $${paramIndex++}`);
      params.push(parseInt(companyId));
    }
    if (issueType !== null) {
      conditions.push(`t.issue_type = $${paramIndex++}`);
      params.push(parseInt(issueType));
    }
    if (subIssueType !== null) {
      conditions.push(`t.sub_issue_type = $${paramIndex++}`);
      params.push(parseInt(subIssueType));
    }

    // Always exclude deleted tickets
    conditions.push(`t.is_deleted = false`);

    const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';

    // Query tickets with issue type and sub-issue type information
    const query = `
      SELECT 
        t.id,
        t.ticket_number,
        t.title,
        t.description,
        t.status,
        t.priority,
        t.issue_type,
        t.sub_issue_type,
        t.company_id,
        t.assigned_resource_id,
        t.contact_id,
        t.create_date,
        t.due_date_time,
        t.completed_date,
        t.last_activity_date,
        it.label as issue_type_label,
        it.is_active as issue_type_active,
        sit.label as sub_issue_type_label,
        sit.is_active as sub_issue_type_active,
        sit.parent_value as sub_issue_parent_value,
        pit.label as parent_issue_type_label,
        c.company_name,
        r.first_name as resource_first_name,
        r.last_name as resource_last_name,
        r.email as resource_email,
        co.first_name as contact_first_name,
        co.last_name as contact_last_name,
        co.email_address as contact_email
      FROM tickets t
      LEFT JOIN issue_types it ON t.issue_type = it.value
      LEFT JOIN sub_issue_types sit ON t.sub_issue_type = sit.value
      LEFT JOIN issue_types pit ON sit.parent_value = pit.value
      LEFT JOIN companies c ON t.company_id = c.id
      LEFT JOIN resources r ON t.assigned_resource_id = r.id
      LEFT JOIN contacts co ON t.contact_id = co.id
      ${whereClause}
      ORDER BY t.create_date DESC
      LIMIT $${paramIndex++}
      OFFSET $${paramIndex++}
    `;

    params.push(limit, offset);

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

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

    const countParams = params.slice(0, -2); // Remove limit and offset
    const countResult = await postgresClient.query(countQuery, countParams);
    const totalCount = parseInt(countResult.rows[0].total);

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