import { requireAuth } from '~/server/utils/auth';

export default defineEventHandler(async (event) => {
  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);

  try {
    const query = getQuery(event);
    const { interestId } = query;
    
    if (!interestId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Interest ID is required',
      });
    }

    console.log('[Test EOI Cleanup] Starting cleanup test for interest:', interestId);

    // First, check current state
    const beforeUpdate = await getInterestById(interestId.toString());
    console.log('[Test EOI Cleanup] BEFORE UPDATE - Current state:', {
      documensoID: beforeUpdate['documensoID'],
      signatureLinks: {
        client: beforeUpdate['Signature Link Client'],
        cc: beforeUpdate['Signature Link CC'],
        developer: beforeUpdate['Signature Link Developer']
      },
      embeddedLinks: {
        client: beforeUpdate['EmbeddedSignatureLinkClient'],
        cc: beforeUpdate['EmbeddedSignatureLinkCC'], 
        developer: beforeUpdate['EmbeddedSignatureLinkDeveloper']
      },
      eoiStatus: beforeUpdate['EOI Status'],
      salesLevel: beforeUpdate['Sales Process Level']
    });

    // Prepare the cleanup data - trying different approaches
    const cleanupData = {
      'EOI Status': 'Awaiting Further Details' as EOIStatus,
      'Sales Process Level': 'Specific Qualified Interest' as InterestSalesProcessLevel,
      'EOI Time Sent': undefined,
      'Signature Link Client': undefined,
      'Signature Link CC': undefined,
      'Signature Link Developer': undefined,
      'EmbeddedSignatureLinkClient': undefined,
      'EmbeddedSignatureLinkCC': undefined,
      'EmbeddedSignatureLinkDeveloper': undefined,
      'documensoID': undefined
    };

    console.log('[Test EOI Cleanup] Cleanup data to send:', cleanupData);

    // Perform the update
    await updateInterest(interestId.toString(), cleanupData);
    
    console.log('[Test EOI Cleanup] Update completed, checking result...');

    // Check the state after update
    const afterUpdate = await getInterestById(interestId.toString());
    console.log('[Test EOI Cleanup] AFTER UPDATE - New state:', {
      documensoID: afterUpdate['documensoID'],
      signatureLinks: {
        client: afterUpdate['Signature Link Client'],
        cc: afterUpdate['Signature Link CC'],
        developer: afterUpdate['Signature Link Developer']
      },
      embeddedLinks: {
        client: afterUpdate['EmbeddedSignatureLinkClient'],
        cc: afterUpdate['EmbeddedSignatureLinkCC'],
        developer: afterUpdate['EmbeddedSignatureLinkDeveloper']
      },
      eoiStatus: afterUpdate['EOI Status'],
      salesLevel: afterUpdate['Sales Process Level']
    });

    // Compare before and after
    const changes = {
      documensoID: {
        before: beforeUpdate['documensoID'],
        after: afterUpdate['documensoID'],
        changed: beforeUpdate['documensoID'] !== afterUpdate['documensoID']
      },
      signatureLinks: {
        client: {
          before: beforeUpdate['Signature Link Client'],
          after: afterUpdate['Signature Link Client'],
          changed: beforeUpdate['Signature Link Client'] !== afterUpdate['Signature Link Client']
        },
        cc: {
          before: beforeUpdate['Signature Link CC'],
          after: afterUpdate['Signature Link CC'],
          changed: beforeUpdate['Signature Link CC'] !== afterUpdate['Signature Link CC']
        },
        developer: {
          before: beforeUpdate['Signature Link Developer'],
          after: afterUpdate['Signature Link Developer'],
          changed: beforeUpdate['Signature Link Developer'] !== afterUpdate['Signature Link Developer']
        }
      },
      embeddedLinks: {
        client: {
          before: beforeUpdate['EmbeddedSignatureLinkClient'],
          after: afterUpdate['EmbeddedSignatureLinkClient'],
          changed: beforeUpdate['EmbeddedSignatureLinkClient'] !== afterUpdate['EmbeddedSignatureLinkClient']
        },
        cc: {
          before: beforeUpdate['EmbeddedSignatureLinkCC'],
          after: afterUpdate['EmbeddedSignatureLinkCC'],
          changed: beforeUpdate['EmbeddedSignatureLinkCC'] !== afterUpdate['EmbeddedSignatureLinkCC']
        },
        developer: {
          before: beforeUpdate['EmbeddedSignatureLinkDeveloper'],
          after: afterUpdate['EmbeddedSignatureLinkDeveloper'],
          changed: beforeUpdate['EmbeddedSignatureLinkDeveloper'] !== afterUpdate['EmbeddedSignatureLinkDeveloper']
        }
      }
    };

    console.log('[Test EOI Cleanup] Change analysis:', changes);

    return {
      success: true,
      message: 'EOI cleanup test completed',
      before: beforeUpdate,
      after: afterUpdate,
      changes,
      cleanupData
    };

  } catch (error: any) {
    console.error('[Test EOI Cleanup] Failed:', error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || error.message || 'Failed to test EOI cleanup',
    });
  }
});
