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

export default defineEventHandler(async (event) => {
  console.log('[check-signature-status] Request received');

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

  try {
    const query = getQuery(event);
    const interestId = query.interestId as string;
    const documentId = query.documentId as string;
    
    console.log('[check-signature-status] Request params:', { interestId, documentId });
    
    if (!interestId && !documentId) {
      throw createError({
        statusCode: 400,
        statusMessage: 'Either interest ID or document ID is required',
      });
    }
    
    // If we have a document ID, check directly
    if (documentId) {
      console.log('[check-signature-status] Using provided document ID:', documentId);
      const status = await checkDocumentSignatureStatus(parseInt(documentId));
      return {
        success: true,
        ...status
      };
    }
    
    // Get the interest to check for stored documensoID
    const interest = await getInterestById(interestId);
    console.log('[check-signature-status] Interest retrieved:', {
      id: interest.Id,
      documensoID: interest['documensoID'],
      documensoID_type: typeof interest['documensoID'],
      has_signature_links: !!(interest['Signature Link Client'] || interest['Signature Link CC'] || interest['Signature Link Developer'])
    });
    
    // If we have a stored documensoID, use it directly
    if (interest && interest['documensoID']) {
      console.log('[check-signature-status] Using stored documensoID:', interest['documensoID']);
      try {
        const status = await checkDocumentSignatureStatus(parseInt(interest['documensoID']));
        return {
          success: true,
          documentId: parseInt(interest['documensoID']),
          ...status
        };
      } catch (error: any) {
        console.error('[check-signature-status] Failed to check status for stored documensoID:', error);
        
        // If document not found (404), clean up the database
        if (error.status === 404 || error.statusCode === 404 || error.message?.includes('404')) {
          console.log('[check-signature-status] Document not found - 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
          };

          await updateInterest(interestId, updateData);
          
          throw createError({
            statusCode: 404,
            statusMessage: 'Document not found - database cleaned up',
          });
        }
        
        // Re-throw other errors
        throw error;
      }
    }
    
    // Otherwise, try to find by external ID (using interestId) - fallback method
    console.log('[check-signature-status] No documensoID stored, trying external ID fallback');
    const externalId = `loi-${interestId}`;
    const document = await getDocumensoDocumentByExternalId(externalId);
    
    if (!document) {
      console.log('[check-signature-status] No document found by external ID either');
      throw createError({
        statusCode: 404,
        statusMessage: 'Document not found for this interest - no documensoID stored and external ID lookup failed',
      });
    }
    
    console.log('[check-signature-status] Found document by external ID:', document.id);
    const status = await checkDocumentSignatureStatus(document.id);
    
    return {
      success: true,
      documentId: document.id,
      ...status
    };
  } catch (error: any) {
    console.error('[check-signature-status] Failed to check signature status:', error);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || 'Failed to check signature status',
    });
  }
});
