import { NextRequest, NextResponse } from 'next/server';
import { getAutotaskClient } from '@/lib/services/autotask-factory';
import { apiCache } from '@/lib/services/cache';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const contactId = parseInt(id);
    
    if (isNaN(contactId)) {
      return NextResponse.json(
        { error: 'Invalid contact ID' },
        { status: 400 }
      );
    }
    
    const cacheKey = `contact:${contactId}`;
    
    // Check cache first
    const cached = apiCache.get(cacheKey);
    if (cached) {
      return NextResponse.json(cached);
    }
    
    const autotaskClient = getAutotaskClient();
    
    // Query for the contact by ID
    const contacts = await autotaskClient.queryEntity('Contacts', {
      filter: [{ op: 'eq', field: 'id', value: contactId }],
    });
    
    const contact = contacts.length > 0 ? contacts[0] : null;
    
    // Cache for 10 minutes (even if null to avoid repeated failed lookups)
    apiCache.set(cacheKey, { contact }, 10 * 60);
    
    return NextResponse.json({ contact });
  } catch (error) {
    const { id } = await params;
    console.error(`Error fetching contact ${id}:`, error);
    const errorMessage = error instanceof Error && error.message 
      ? error.message 
      : 'Failed to fetch contact from Autotask';
    
    // Return 200 with null contact instead of 500 to prevent UI errors
    // The contact might not exist or might not be accessible
    return NextResponse.json(
      { contact: null, error: errorMessage }
    );
  }
}
