import { getInterestById, updateInterest } from '~/server/utils/nocodb';
import { getDocumensoDocument } from '~/server/utils/documeso';
import { requireAuth } from '~/server/utils/auth';
import type { InterestSalesProcessLevel, EOIStatus } from '~/utils/types';

export default defineEventHandler(async (event) => {
  console.log('[Validate Document] Request received');

  // Check authentication (x-tag header OR Keycloak session)
  await requireAuth(event);

  try {
    const query = getQuery(event);
    const { interestId } = query;
    
    console.log('[Validate Document] Interest ID:', interestId);
    
    if (!interestId) {
      console.error('[Validate Document] No interest ID provided');
      throw createError({
        statusCode: 400,
        statusMessage: 'Interest ID is required',
      });
    }

    // Get current interest data
    const interest = await getInterestById(interestId.toString());
    if (!interest) {
      throw createError({
        statusCode: 404,
        statusMessage: 'Interest not found',
      });
    }

    const documensoID = interest['documensoID'];
    console.log('[Validate Document] Documenso ID:', documensoID);

    // If no documensoID, the state is already clean
    if (!documensoID) {
      console.log('[Validate Document] No documensoID found - state is clean');
      return {
        success: true,
        valid: true,
        message: 'No document ID found - state is clean',
        cleaned: false
      };
    }

    // Try to fetch the document from Documenso
    let documentExists = true;
    let documentStatus = null;
    
    try {
      console.log('[Validate Document] Checking document existence in Documenso');
      const document = await getDocumensoDocument(parseInt(documensoID));
      documentStatus = document.status;
      console.log('[Validate Document] Document exists with status:', documentStatus);
    } catch (error: any) {
      console.log('[Validate Document] Document check failed:', error.message);
      
      // If it's a 404 or similar error, the document doesn't exist
      if (error.status === 404 || error.statusCode === 404 || error.message?.includes('404')) {
        documentExists = false;
        console.log('[Validate Document] Document not found in Documenso - will clean up database');
      } else {
        // For other errors, we'll assume the document exists but there's a connection issue
        console.warn('[Validate Document] Unable to verify document existence due to API error:', error.message);
        return {
          success: true,
          valid: true,
          message: 'Unable to verify document existence due to API error',
          cleaned: false,
          error: error.message
        };
      }
    }

    // If document doesn't exist, clean up the database
    if (!documentExists) {
      console.log('[Validate Document] Cleaning up orphaned database records');
      
      const updateData = {
        '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,
        'reminder_enabled': false
      };

      // Update the interest
      await updateInterest(interestId.toString(), updateData);
      
      console.log('[Validate Document] Database cleanup completed');
      
      return {
        success: true,
        valid: false,
        message: 'Document not found in Documenso - database cleaned up',
        cleaned: true
      };
    }

    // Document exists and is valid
    return {
      success: true,
      valid: true,
      message: 'Document exists and is valid',
      cleaned: false,
      documentStatus
    };

  } catch (error: any) {
    console.error('[Validate Document] Failed to validate document:', error);
    console.error('[Validate Document] Error stack:', error.stack);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || error.message || 'Failed to validate document',
    });
  }
});
