/**
 * Last Sync Info API Endpoint
 * GET /api/sync/last-sync - Get last sync information for all entities
 */

import { NextResponse } from 'next/server';
import { AutotaskClient } from '@/lib/services/autotask-client';
import { createSyncService } from '@/lib/services/sync-service';

export async function GET() {
  try {
    // Initialize Autotask client
    const autotaskClient = new AutotaskClient({
      apiUrl: process.env.AUTOTASK_API_URL || '',
      username: process.env.AUTOTASK_USERNAME || '',
      password: process.env.AUTOTASK_SECRET || '',
      apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
    });

    // Create sync service
    const syncService = createSyncService(autotaskClient);

    // Get last sync info
    const lastSyncMap = await syncService.getLastSyncInfo();

    // Convert Map to object for JSON serialization
    const lastSyncInfo: Record<string, any> = {};
    lastSyncMap.forEach((value, key) => {
      lastSyncInfo[key] = value;
    });

    return NextResponse.json({
      lastSync: lastSyncInfo,
    });
  } catch (error) {
    console.error('Failed to fetch last sync info:', error);
    return NextResponse.json(
      { error: 'Failed to fetch last sync info' },
      { status: 500 }
    );
  }
}
