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

export async function POST(request: NextRequest) {
  try {
    const { contactIds } = await request.json();
    
    if (!Array.isArray(contactIds) || contactIds.length === 0) {
      return NextResponse.json({ contacts: {} });
    }
    
    // Remove duplicates
    const uniqueIds = [...new Set(contactIds)];
    
    // Check cache first
    const contacts: Record<number, any> = {};
    const uncachedIds: number[] = [];
    
    for (const id of uniqueIds) {
      const cacheKey = `contact:${id}`;
      const cached = apiCache.get(cacheKey) as { contact: any } | undefined;
      if (cached && cached.contact) {
        contacts[id] = cached.contact;
      } else {
        uncachedIds.push(id);
      }
    }
    
    // Fetch uncached contacts with rate limiting
    if (uncachedIds.length > 0) {
      const autotaskClient = getAutotaskClient();
      
      try {
        // Fetch contacts one by one but with rate limiting built into the client
        // This is better than trying to use OR filters which Autotask doesn't support well
        const fetchPromises = uncachedIds.map(async (id) => {
          try {
            const fetchedContacts = await autotaskClient.queryEntity('Contacts', {
              filter: [{ op: 'eq', field: 'id', value: id }]
            });
            
            if (fetchedContacts.length > 0) {
              const contact = fetchedContacts[0];
              contacts[id] = contact;
              
              // Cache the contact
              const cacheKey = `contact:${id}`;
              apiCache.set(cacheKey, { contact }, 10 * 60);
            } else {
              // Mark as not found
              contacts[id] = null;
              const cacheKey = `contact:${id}`;
              apiCache.set(cacheKey, { contact: null }, 10 * 60);
            }
          } catch (error) {
            console.error(`Error fetching contact ${id}:`, error);
            contacts[id] = null;
            const cacheKey = `contact:${id}`;
            apiCache.set(cacheKey, { contact: null }, 10 * 60);
          }
        });
        
        // Wait for all fetches to complete
        await Promise.all(fetchPromises);
      } catch (error) {
        console.error('Error fetching batch contacts:', error);
        // Return what we have from cache
      }
    }
    
    return NextResponse.json({ contacts });
  } catch (error) {
    console.error('Error in batch contact fetch:', error);
    return NextResponse.json({ contacts: {} });
  }
}
