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

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

  console.log('[Delete Generated EOI] Request received');

  try {
    const body = await readBody(event);
    const { interestId } = body;
    
    console.log('[Delete Generated EOI] Interest ID:', interestId);
    
    if (!interestId) {
      console.error('[Delete Generated EOI] No interest ID provided');
      throw createError({
        statusCode: 400,
        statusMessage: 'Interest ID is required',
      });
    }

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

    const documensoID = interest['documensoID'];
    console.log('[Delete Generated EOI] Documenso ID:', documensoID);

    if (!documensoID) {
      throw createError({
        statusCode: 400,
        statusMessage: 'No generated document found to delete',
      });
    }

    // Check if document is fully signed - prevent deletion if it is
    try {
      const signatureStatus = await checkDocumentSignatureStatus(parseInt(documensoID));
      console.log('[Delete Generated EOI] Signature status:', signatureStatus);
      
      if (signatureStatus.allSigned) {
        throw createError({
          statusCode: 400,
          statusMessage: 'Cannot delete a fully signed document. All parties have already signed.',
        });
      }
    } catch (error: any) {
      console.error('[Delete Generated EOI] Failed to check signature status:', error);
      
      // If it's a 404 error, the document is already gone from Documenso, so we can proceed with cleanup
      if (error.status === 404 || error.statusCode === 404 || error.message?.includes('404')) {
        console.log('[Delete Generated EOI] Document not found in Documenso (404) - proceeding with database cleanup');
      } else {
        console.warn('[Delete Generated EOI] Proceeding with deletion despite signature status check failure');
      }
    }

    // Delete document from Documenso
    const documensoApiKey = process.env.NUXT_DOCUMENSO_API_KEY;
    const documensoBaseUrl = process.env.NUXT_DOCUMENSO_BASE_URL;
    
    if (!documensoApiKey || !documensoBaseUrl) {
      throw createError({ 
        statusCode: 500, 
        statusMessage: "Documenso configuration missing. Please check NUXT_DOCUMENSO_API_KEY and NUXT_DOCUMENSO_BASE_URL environment variables." 
      });
    }

    console.log('[Delete Generated EOI] Deleting document from Documenso');
    let documensoDeleteSuccessful = false;
    
    try {
      const deleteResponse = await fetch(`${documensoBaseUrl}/api/v1/documents/${documensoID}`, {
        method: 'DELETE',
        headers: {
          'Authorization': `Bearer ${documensoApiKey}`,
          'Content-Type': 'application/json'
        }
      });

      if (!deleteResponse.ok) {
        const errorText = await deleteResponse.text();
        console.error('[Delete Generated EOI] Documenso deletion failed:', errorText);
        
        // If it's a 404, the document is already gone, which is what we want
        if (deleteResponse.status === 404) {
          console.log('[Delete Generated EOI] Document already deleted from Documenso (404) - proceeding with database cleanup');
          documensoDeleteSuccessful = true;
        } else {
          throw new Error(`Failed to delete document from Documenso: ${deleteResponse.statusText}`);
        }
      } else {
        console.log('[Delete Generated EOI] Successfully deleted document from Documenso');
        documensoDeleteSuccessful = true;
      }
    } catch (error: any) {
      console.error('[Delete Generated EOI] Documenso deletion error:', error);
      
      // Check if it's a network error or 404 - in those cases, proceed with cleanup
      if (error.message?.includes('404') || error.status === 404) {
        console.log('[Delete Generated EOI] Document not found in Documenso - proceeding with database cleanup');
        documensoDeleteSuccessful = true;
      } else {
        throw createError({
          statusCode: 500,
          statusMessage: `Failed to delete document from Documenso: ${error.message}`,
        });
      }
    }

    if (!documensoDeleteSuccessful) {
      throw createError({
        statusCode: 500,
        statusMessage: 'Failed to delete document from Documenso',
      });
    }

    // Reset interest fields
    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
    };

    console.log('[Delete Generated EOI] Resetting interest fields');
    
    // Update the interest
    await updateInterest(interestId, updateData);
    
    console.log('[Delete Generated EOI] Delete completed successfully');
    return {
      success: true,
      message: 'Generated EOI document deleted successfully',
    };
  } catch (error: any) {
    console.error('[Delete Generated EOI] Failed to delete generated EOI document:', error);
    console.error('[Delete Generated EOI] Error stack:', error.stack);
    throw createError({
      statusCode: error.statusCode || 500,
      statusMessage: error.statusMessage || error.message || 'Failed to delete generated EOI document',
    });
  }
});
