/**
 * Real Scenario Email Test
 * 
 * Test emails with realistic workflow data
 * Simulates: User 10 creates request, User 12 is approver
 */

import { emailNotificationService } from '../services/emailNotification.service';
import logger from '../utils/logger';

const appDomain = process.env.APP_DOMAIN || 'royalenfield.com';

/**
 * Simulate real workflow scenario
 */
async function testRealScenario() {
  console.log('🧪 Testing Real Workflow Scenario\n');
  console.log('Scenario: User 10 creates request, assigns to User 12 as approver\n');

  // Mock user data (simulating real database records)
  const user10 = {
    userId: 'user-10-uuid',
    email: `john.doe@${appDomain}`,
    displayName: 'John Doe',
    department: 'Engineering',
    designation: 'Senior Engineer'
  };

  const user12 = {
    userId: 'user-12-uuid',
    email: `jane.smith@${appDomain}`,
    displayName: 'Jane Smith',
    department: 'Management',
    designation: 'Engineering Manager',
    levelNumber: 1
  };

  // Mock request data (simulating real workflow request)
  const requestData = {
    requestId: 'req-uuid-12345',
    requestNumber: 'REQ-2025-12-0013',
    title: 'New Equipment Purchase Request - Testing Department',
    description: `
      <h3>Equipment Purchase Request</h3>
      <p>Requesting approval for the following equipment for the <strong>testing department</strong>:</p>
      <ul>
        <li><strong>2× Royal Enfield Himalayan</strong> (Latest 2025 model)</li>
        <li><strong>Safety gear package</strong> - Helmets, jackets, gloves</li>
        <li><strong>Maintenance toolkit</strong> - Standard service equipment</li>
      </ul>
      <h4>Budget Breakdown</h4>
      <p>Total estimated cost: <strong>₹15,00,000</strong></p>
      <blockquote>
        This purchase is critical for our Q1 2025 testing schedule and has been pre-approved by the department head.
      </blockquote>
      <p>Please review and approve at your earliest convenience.</p>
      <p>For questions, contact: <a href="mailto:john.doe@${appDomain}">john.doe@${appDomain}</a></p>
    `,
    requestType: 'Purchase',
    priority: 'HIGH',
    createdAt: new Date(),
    tatHours: 48,
    totalApprovers: 3,
    initiatorName: user10.displayName,
    initiatorId: user10.userId
  };

  // Mock approval chain for multi-level scenario
  const approvalChain = [
    {
      levelNumber: 1,
      approverName: 'Jane Smith',
      approverEmail: `jane.smith@${appDomain}`,
      status: 'PENDING',
      approvedAt: null
    },
    {
      levelNumber: 2,
      approverName: 'Michael Brown',
      approverEmail: `michael.brown@${appDomain}`,
      status: 'PENDING',
      approvedAt: null
    },
    {
      levelNumber: 3,
      approverName: 'Sarah Johnson',
      approverEmail: `sarah.johnson@${appDomain}`,
      status: 'PENDING',
      approvedAt: null
    }
  ];

  try {
    console.log('─'.repeat(80));
    console.log('📧 Test 1: Request Created Email (to Initiator - User 10)');
    console.log('─'.repeat(80));

    await emailNotificationService.sendRequestCreated(
      requestData,
      user10,
      user12
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 2: Multi-Level Approval Request Email (to Approver - User 12)');
    console.log('─'.repeat(80));

    await emailNotificationService.sendApprovalRequest(
      requestData,
      user12,
      user10,
      true, // isMultiLevel
      approvalChain
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 3: TAT Reminder at 40% (Configurable Threshold)');
    console.log('─'.repeat(80));

    await emailNotificationService.sendTATReminder(
      requestData,
      user12,
      {
        thresholdPercentage: 40,
        timeRemaining: '28 hours',
        tatDeadline: new Date(Date.now() + 28 * 60 * 60 * 1000),
        assignedDate: requestData.createdAt
      }
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 4: TAT Reminder at 80% (Configurable Threshold)');
    console.log('─'.repeat(80));

    await emailNotificationService.sendTATReminder(
      requestData,
      user12,
      {
        thresholdPercentage: 80,
        timeRemaining: '9 hours',
        tatDeadline: new Date(Date.now() + 9 * 60 * 60 * 1000),
        assignedDate: requestData.createdAt
      }
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 5: Approval Confirmation (User 12 approved)');
    console.log('─'.repeat(80));

    const approvedUser12 = {
      ...user12,
      approvedAt: new Date(),
      comments: `
        <p>Approved! The equipment purchase is justified for the testing schedule.</p>
        <p><strong>Conditions:</strong></p>
        <ul>
          <li>Purchase must be completed by January 15, 2025</li>
          <li>Get quotes from at least 2 vendors</li>
          <li>Include extended warranty</li>
        </ul>
      `
    };

    await emailNotificationService.sendApprovalConfirmation(
      requestData,
      approvedUser12,
      user10,
      false, // not final approval
      { displayName: 'Michael Brown', email: `michael.brown@${appDomain}` }
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 6: TAT Breached (100%)');
    console.log('─'.repeat(80));

    await emailNotificationService.sendTATBreached(
      requestData,
      user12,
      {
        timeOverdue: '6 hours overdue',
        tatDeadline: new Date(Date.now() - 6 * 60 * 60 * 1000),
        assignedDate: requestData.createdAt
      }
    );

    console.log('\n');
    console.log('─'.repeat(80));
    console.log('📧 Test 7: Request Closed (with conclusion)');
    console.log('─'.repeat(80));

    const closedRequestData = {
      ...requestData,
      closedAt: new Date(),
      totalApprovals: 3
    };

    await emailNotificationService.sendRequestClosed(
      closedRequestData,
      user10,
      {
        conclusionRemark: `
          <h3>Project Successfully Completed</h3>
          <p>All equipment has been purchased and delivered to the testing department.</p>
          <h4>Final Summary:</h4>
          <ul>
            <li>2× Royal Enfield Himalayan delivered on Jan 10, 2025</li>
            <li>Safety gear distributed to team members</li>
            <li>Maintenance toolkit installed in workshop</li>
          </ul>
          <p><strong>Total cost:</strong> ₹14,85,000 (within budget)</p>
          <blockquote>
            Testing department is now fully equipped for Q1 2025 schedule. All deliverables met.
          </blockquote>
        `,
        workNotesCount: 15,
        documentsCount: 8
      }
    );

    console.log('\n');
    console.log('═'.repeat(80));
    console.log('✅ All Real Scenario Tests Complete!');
    console.log('═'.repeat(80));
    console.log('\n💡 Check the Preview URLs above to see emails with REAL data!');
    console.log('📌 All emails use actual request information, rich text content, and workflow data');
    console.log('\n');

  } catch (error) {
    console.error('❌ Test failed:', error);
    throw error;
  }
}

// Run the test
console.log('\n');
console.log('═'.repeat(80));
console.log('  REAL SCENARIO EMAIL TEST');
console.log('  User 10 (John Doe) → Creates Request');
console.log('  User 12 (Jane Smith) → Assigned as Approver');
console.log('═'.repeat(80));
console.log('\n');

testRealScenario()
  .then(() => {
    console.log('✅ Test completed successfully\n');
    process.exit(0);
  })
  .catch((error) => {
    console.error('❌ Test failed:', error);
    process.exit(1);
  });
