import { NextRequest, NextResponse } from 'next/server';
import { getAutotaskClient } from '@/lib/services/autotask-factory';
import { Ticket } from '@/lib/types/autotask';
import { getCachedData, setCachedData } from '@/lib/services/redis-client';

export async function GET(request: NextRequest) {
  try {
    // Check if API is configured
    if (!process.env.AUTOTASK_API_URL || 
        !process.env.AUTOTASK_USERNAME || 
        !process.env.AUTOTASK_SECRET || 
        !process.env.AUTOTASK_API_INTEGRATION_CODE) {
      return NextResponse.json(
        { 
          error: 'Autotask API not configured',
          message: 'Please set up your environment variables. Check /api/health for details.'
        },
        { status: 503 }
      );
    }

    const client = getAutotaskClient();
    const searchParams = request.nextUrl.searchParams;
    const resourceId = searchParams.get('resourceId');
    const companyId = searchParams.get('companyId');

    let tickets: Ticket[] = [];

    if (resourceId) {
      tickets = await client.getOpenTicketsByResource(parseInt(resourceId));
    } else if (companyId) {
      tickets = await client.getTicketsByCompany(parseInt(companyId));
    } else {
      // Get all open tickets
      tickets = await client.queryEntity<Ticket>('Tickets', {
        filter: [{ op: 'noteq', field: 'status', value: 5 }],
      });
    }

    return NextResponse.json({ tickets });
  } catch (error) {
    console.error('Error fetching tickets:', error);
    
    // Provide more detailed error information
    if (error instanceof Error) {
      if (error.message.includes('Missing Autotask API configuration')) {
        return NextResponse.json(
          { 
            error: 'API Configuration Error',
            message: 'Autotask API credentials are not properly configured. Please check your .env.local file.',
            details: error.message
          },
          { status: 503 }
        );
      }
      
      return NextResponse.json(
        { 
          error: 'Failed to fetch tickets',
          message: error.message,
          hint: 'Check the console for more details or visit /api/health to diagnose the issue'
        },
        { status: 500 }
      );
    }
    
    return NextResponse.json(
      { error: 'An unexpected error occurred while fetching tickets' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const client = getAutotaskClient();
    const body = await request.json();
    
    const ticket = await client.createTicket(body);
    
    return NextResponse.json({ ticket });
  } catch (error) {
    console.error('Error creating ticket:', error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Failed to create ticket' },
      { status: 500 }
    );
  }
}
