/**
 * Basic API Test
 * Simple test to verify API endpoint functionality
 */

const inventoryCalculationService = require('./services/inventoryCalculationService');
const materialUtilizationService = require('./services/materialUtilizationService');
const bomDimensionService = require('./services/bomDimensionService');

/**
 * Test basic service functionality
 */
async function testBasicServices() {
  console.log('=== Testing Basic Services ===');
  
  try {
    // Test 1: Mock RM inventory pieces
    const mockPieces = [
      {
        id: 1,
        product_id: 1,
        piece_number: 1,
        length: 6.0,
        width: 4.0,
        unit: 'm',
        status: 'FULL',
        cost_per_area: 15.50,
        created_at: new Date()
      },
      {
        id: 2,
        product_id: 1,
        piece_number: 2,
        length: 3.0,
        width: 2.0,
        unit: 'm',
        status: 'USABLE',
        usable_length: 2.5,
        usable_width: 1.8,
        cost_per_area: 15.50,
        created_at: new Date()
      },
      {
        id: 3,
        product_id: 1,
        piece_number: 3,
        length: 1.5,
        width: 1.0,
        unit: 'm',
        status: 'WASTE',
        usable_length: 1.5,
        usable_width: 1.0,
        cost_per_area: 15.50,
        created_at: new Date()
      }
    ];
    
    console.log('✓ Created mock RM inventory pieces:', mockPieces.length);
    
    // Test 2: Inventory calculation service
    const summaryResult = inventoryCalculationService.calculateInventorySummary(mockPieces, {
      targetUnit: 'm',
      groupByStatus: true,
      includeUtilizationMetrics: true
    });
    
    if (summaryResult.isValid) {
      console.log('✓ Inventory summary calculation successful');
      console.log('  - Total pieces:', summaryResult.summary.totalPieces);
      console.log('  - Total area:', summaryResult.summary.totalArea.toFixed(2), 'm²');
      console.log('  - Status breakdown:', Object.keys(summaryResult.summary.statusBreakdown));
    } else {
      console.log('✗ Inventory summary calculation failed:', summaryResult.error);
    }
    
    // Test 3: Material utilization service
    const utilizationResult = materialUtilizationService.calculateUtilizationStatistics(mockPieces, {
      timeRange: { days: 30 },
      includeWasteAnalysis: true
    });
    
    if (utilizationResult.isValid) {
      console.log('✓ Material utilization calculation successful');
      console.log('  - Efficiency score:', utilizationResult.statistics.efficiencyScore?.toFixed(2) || 'N/A');
    } else {
      console.log('✗ Material utilization calculation failed:', utilizationResult.error);
    }
    
    // Test 4: BOM dimension validation
    const mockBOMItem = {
      id: 1,
      rm_product_id: 1,
      use_dimensions: true,
      required_length: 2.0,
      required_width: 1.5,
      dimension_unit: 'm'
    };
    
    const mockRMProduct = {
      id: 1,
      name: 'Cotton Fabric',
      product_type: 'RM',
      track_by_dimensions: true,
      unit_of_measure: 'm'
    };
    
    const dimensionValidation = bomDimensionService.validateBOMItemDimensions(mockBOMItem, mockRMProduct);
    
    if (dimensionValidation.isValid) {
      console.log('✓ BOM dimension validation successful');
      console.log('  - Uses dimensions:', dimensionValidation.useDimensions);
      console.log('  - Required dimensions:', dimensionValidation.dimensions);
    } else {
      console.log('✗ BOM dimension validation failed:', dimensionValidation.error);
    }
    
    // Test 5: Dimension requirements calculation
    const dimensionReq = bomDimensionService.calculateDimensionRequirements(mockBOMItem, 5);
    
    if (dimensionReq.isValid) {
      console.log('✓ Dimension requirements calculation successful');
      console.log('  - Area per unit:', dimensionReq.areaPerUnit, 'm²');
      console.log('  - Total area required:', dimensionReq.totalAreaRequired, 'm²');
    } else {
      console.log('✗ Dimension requirements calculation failed:', dimensionReq.error);
    }
    
    return { success: true };
    
  } catch (error) {
    console.log('✗ Basic services test failed:', error.message);
    return { success: false, error: error.message };
  }
}

/**
 * Test API validation logic
 */
async function testAPIValidationLogic() {
  console.log('\n=== Testing API Validation Logic ===');
  
  try {
    // Test 1: RM inventory piece validation
    const validRMPiece = {
      product_id: 1,
      piece_length: 2.5,
      piece_width: 1.8,
      dimension_unit: 'm',
      pieces_count: 3
    };
    
    const isValidRMPiece = validRMPiece.product_id > 0 &&
                          validRMPiece.piece_length > 0 &&
                          validRMPiece.piece_width > 0 &&
                          ['inch', 'cm', 'm'].includes(validRMPiece.dimension_unit) &&
                          validRMPiece.pieces_count > 0;
    
    console.log('✓ RM piece validation:', isValidRMPiece ? 'PASS' : 'FAIL');
    
    // Test 2: BOM item validation
    const validBOMItem = {
      rm_product_id: 1,
      use_dimensions: true,
      required_length: 2.0,
      required_width: 1.5,
      dimension_unit: 'm'
    };
    
    const isValidBOMItem = validBOMItem.rm_product_id > 0 &&
                          validBOMItem.use_dimensions === true &&
                          validBOMItem.required_length > 0 &&
                          validBOMItem.required_width > 0 &&
                          ['inch', 'cm', 'm'].includes(validBOMItem.dimension_unit);
    
    console.log('✓ BOM item validation:', isValidBOMItem ? 'PASS' : 'FAIL');
    
    // Test 3: Write-off request validation
    const validWriteOff = {
      piece_ids: [1, 2, 3],
      reason: 'Damaged during handling',
      notes: 'Water damage'
    };
    
    const isValidWriteOff = Array.isArray(validWriteOff.piece_ids) &&
                           validWriteOff.piece_ids.length > 0 &&
                           validWriteOff.piece_ids.every(id => Number.isInteger(id) && id > 0) &&
                           validWriteOff.reason &&
                           validWriteOff.reason.length >= 3;
    
    console.log('✓ Write-off validation:', isValidWriteOff ? 'PASS' : 'FAIL');
    
    // Test 4: Query parameter validation
    const validQuery = {
      status: 'FULL',
      min_length: 1.0,
      max_length: 10.0,
      min_width: 0.5,
      max_width: 5.0,
      unit: 'm',
      page: 1,
      limit: 50
    };
    
    const isValidQuery = ['FULL', 'USABLE', 'WASTE', 'SCRAP'].includes(validQuery.status) &&
                        validQuery.min_length >= 0 &&
                        validQuery.max_length >= validQuery.min_length &&
                        validQuery.min_width >= 0 &&
                        validQuery.max_width >= validQuery.min_width &&
                        ['inch', 'cm', 'm'].includes(validQuery.unit) &&
                        validQuery.page >= 1 &&
                        validQuery.limit >= 1 && validQuery.limit <= 100;
    
    console.log('✓ Query parameter validation:', isValidQuery ? 'PASS' : 'FAIL');
    
    return { success: true };
    
  } catch (error) {
    console.log('✗ API validation logic test failed:', error.message);
    return { success: false, error: error.message };
  }
}

/**
 * Test controller logic simulation
 */
async function testControllerLogic() {
  console.log('\n=== Testing Controller Logic Simulation ===');
  
  try {
    // Test 1: Simulate RM inventory pieces listing
    const mockRequest = {
      params: { productId: '1' },
      query: { 
        status: 'FULL',
        page: '1',
        limit: '50',
        min_length: '1.0',
        unit: 'm'
      }
    };
    
    // Simulate validation
    const productId = parseInt(mockRequest.params.productId);
    const page = parseInt(mockRequest.query.page) || 1;
    const limit = parseInt(mockRequest.query.limit) || 50;
    const status = mockRequest.query.status;
    const minLength = mockRequest.query.min_length ? parseFloat(mockRequest.query.min_length) : null;
    const unit = mockRequest.query.unit;
    
    const isValidRequest = productId > 0 &&
                          page >= 1 &&
                          limit >= 1 && limit <= 100 &&
                          (!status || ['FULL', 'USABLE', 'WASTE', 'SCRAP'].includes(status)) &&
                          (!minLength || minLength >= 0) &&
                          (!unit || ['inch', 'cm', 'm'].includes(unit));
    
    console.log('✓ RM inventory listing simulation:', isValidRequest ? 'PASS' : 'FAIL');
    
    // Test 2: Simulate inventory summary calculation
    const mockPieces = [
      { id: 1, length: 6.0, width: 4.0, unit: 'm', status: 'FULL' },
      { id: 2, length: 3.0, width: 2.0, unit: 'm', status: 'USABLE', usable_length: 2.5, usable_width: 1.8 }
    ];
    
    // Simulate summary calculation
    let totalArea = 0;
    let totalPieces = mockPieces.length;
    const statusCounts = {};
    
    mockPieces.forEach(piece => {
      const area = piece.status === 'FULL' ? 
        piece.length * piece.width :
        (piece.usable_length || piece.length) * (piece.usable_width || piece.width);
      totalArea += area;
      
      statusCounts[piece.status] = (statusCounts[piece.status] || 0) + 1;
    });
    
    const summary = {
      totalPieces,
      totalArea,
      statusCounts
    };
    
    console.log('✓ Inventory summary simulation:', summary.totalPieces > 0 ? 'PASS' : 'FAIL');
    console.log('  - Total pieces:', summary.totalPieces);
    console.log('  - Total area:', summary.totalArea.toFixed(2), 'm²');
    console.log('  - Status counts:', summary.statusCounts);
    
    // Test 3: Simulate write-off operation
    const mockWriteOffRequest = {
      piece_ids: [1, 2],
      reason: 'Damaged during handling',
      notes: 'Water damage from roof leak'
    };
    
    // Simulate write-off validation and processing
    const piecesToWriteOff = mockPieces.filter(p => mockWriteOffRequest.piece_ids.includes(p.id));
    const totalAreaWrittenOff = piecesToWriteOff.reduce((sum, piece) => {
      const area = piece.status === 'FULL' ? 
        piece.length * piece.width :
        (piece.usable_length || piece.length) * (piece.usable_width || piece.width);
      return sum + area;
    }, 0);
    
    console.log('✓ Write-off simulation:', piecesToWriteOff.length > 0 ? 'PASS' : 'FAIL');
    console.log('  - Pieces to write off:', piecesToWriteOff.length);
    console.log('  - Total area written off:', totalAreaWrittenOff.toFixed(2), 'm²');
    
    return { success: true };
    
  } catch (error) {
    console.log('✗ Controller logic simulation failed:', error.message);
    return { success: false, error: error.message };
  }
}

/**
 * Main test runner
 */
async function runBasicAPITest() {
  console.log('🚀 Starting Basic API Test');
  console.log('Testing core functionality without database operations...\n');
  
  const results = {
    basicServices: await testBasicServices(),
    apiValidation: await testAPIValidationLogic(),
    controllerLogic: await testControllerLogic()
  };
  
  // Summary
  console.log('\n=== Test Summary ===');
  const totalTests = Object.keys(results).length;
  const passedTests = Object.values(results).filter(r => r.success).length;
  
  console.log(`Total test suites: ${totalTests}`);
  console.log(`Passed: ${passedTests}`);
  console.log(`Failed: ${totalTests - passedTests}`);
  
  if (passedTests === totalTests) {
    console.log('🎉 All basic API tests passed!');
  } else {
    console.log('❌ Some basic API tests failed');
    
    // Show failed tests
    Object.entries(results).forEach(([testName, result]) => {
      if (!result.success) {
        console.log(`  - ${testName}: ${result.error}`);
      }
    });
  }
  
  return results;
}

// Run the test if this file is executed directly
if (require.main === module) {
  runBasicAPITest()
    .then(() => {
      console.log('\n✅ Basic API Test completed');
      process.exit(0);
    })
    .catch((error) => {
      console.error('\n❌ Basic API Test failed:', error);
      process.exit(1);
    });
}

module.exports = {
  runBasicAPITest,
  testBasicServices,
  testAPIValidationLogic,
  testControllerLogic
};