import { requireAuth } from '~/server/utils/auth';
import { getNocoDbConfiguration, updateInterest, deleteInterest } from '~/server/utils/nocodb';

export default defineEventHandler(async (event) => {
  console.log('[ADMIN] Merge duplicates request');

  try {
    // Require authentication (any authenticated user with interest access)
    await requireAuth(event);

    const body = await readBody(event);
    const { masterId, duplicateIds, mergeData } = body;

    if (!masterId || !duplicateIds || !Array.isArray(duplicateIds)) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Invalid merge request: masterId and duplicateIds array required'
      });
    }

    console.log('[ADMIN] Merging duplicates:', {
      masterId,
      duplicateIds,
      fieldsToMerge: Object.keys(mergeData || {})
    });

    // Update the master record with merged data
    if (mergeData && Object.keys(mergeData).length > 0) {
      console.log('[ADMIN] Updating master record with merged data');
      await updateInterest(masterId.toString(), mergeData);
    }

    // Delete the duplicate records
    const deletionResults = [];
    for (const duplicateId of duplicateIds) {
      try {
        console.log('[ADMIN] Deleting duplicate record:', duplicateId);
        await deleteInterest(duplicateId.toString());
        deletionResults.push({ id: duplicateId, success: true });
      } catch (error: any) {
        console.error('[ADMIN] Failed to delete duplicate:', duplicateId, error);
        deletionResults.push({ 
          id: duplicateId, 
          success: false, 
          error: error.message 
        });
      }
    }

    console.log('[ADMIN] Merge operation completed');

    return {
      success: true,
      data: {
        masterId,
        mergedCount: duplicateIds.length,
        deletionResults,
        updatedFields: Object.keys(mergeData || {})
      }
    };

  } catch (error: any) {
    console.error('[ADMIN] Failed to merge duplicates:', error);
    
    if (error.statusCode === 403) {
      return {
        success: false,
        error: 'Insufficient permissions. Admin access required.'
      };
    }

    if (error.statusCode === 400) {
      return {
        success: false,
        error: error.statusMessage
      };
    }

    return {
      success: false,
      error: 'Failed to merge duplicate records'
    };
  }
});
