/**
 * Test file to verify order data mapping and display
 * 
 * This test simulates the API response and verifies:
 * 1. Order items are correctly mapped with count and productId
 * 2. Order total is correctly calculated and displayed
 * 3. Form fields receive the correct values
 */

// Simulate the API response structure based on the backend entity
interface MockOrderItem {
  id: number;
  orderId: number;
  productId: number | string; // Could be number or string from API
  product: {
    id: number;
    name: string;
    amount: string | number; // Decimal from DB might be string
  };
  count: number | string; // Could be number or string from API
  amountPerTub: string | number;
  totalAmount: string | number;
  postageServiceChargeId?: number | string;
  postageServiceCharge?: {
    id: number;
    name: string;
    amount: string | number;
  };
  deductionNote?: string;
}

interface MockOrder {
  id: number;
  orderNumber: string;
  customerId: number;
  orderItems: MockOrderItem[];
}

// Test data - simulating actual API response
const mockApiResponse: MockOrder = {
  id: 9,
  orderNumber: "ORD-20260129-0001",
  customerId: 11437,
  orderItems: [
    {
      id: 21,
      orderId: 9,
      productId: 3, // Could be number
      product: {
        id: 3,
        name: "test2",
        amount: "50.00", // Decimal from DB is string
      },
      count: 4, // Could be number
      amountPerTub: "50.00",
      totalAmount: "220.00", // Includes postage
      postageServiceChargeId: 2,
      postageServiceCharge: {
        id: 2,
        name: "jay",
        amount: "20.00",
      },
    },
  ],
};

// Test case 1: Map order items correctly
function testMapOrderItems(orderData: MockOrder) {
  console.log("Test 1: Mapping order items");
  console.log("Input orderData:", JSON.stringify(orderData, null, 2));

  const items = orderData.orderItems.map((item) => {
    // Handle count - could be number, string, or null
    let count = 1;
    if (item.count !== null && item.count !== undefined) {
      const parsedCount = Number(item.count);
      if (!isNaN(parsedCount) && parsedCount > 0) {
        count = parsedCount;
      }
    }

    // Handle productId
    let productId = 0;
    if (item.productId !== null && item.productId !== undefined) {
      const parsedProductId = Number(item.productId);
      if (!isNaN(parsedProductId) && parsedProductId > 0) {
        productId = parsedProductId;
      }
    }

    return {
      productId: productId,
      count: count,
    };
  });

  console.log("Mapped items:", items);
  
  // Verify
  const firstItem = items[0];
  const expectedCount = 4;
  const expectedProductId = 3;
  
  const countMatch = firstItem.count === expectedCount;
  const productIdMatch = firstItem.productId === expectedProductId;
  
  console.log(`Count: Expected ${expectedCount}, Got ${firstItem.count}, Match: ${countMatch}`);
  console.log(`ProductId: Expected ${expectedProductId}, Got ${firstItem.productId}, Match: ${productIdMatch}`);
  
  return countMatch && productIdMatch;
}

// Test case 2: Calculate order total
function testCalculateOrderTotal(orderData: MockOrder) {
  console.log("\nTest 2: Calculating order total");
  
  const existingTotal = orderData.orderItems.reduce((sum, item) => {
    if (item.totalAmount) {
      const itemTotal = Number(item.totalAmount);
      if (!isNaN(itemTotal)) {
        return sum + itemTotal;
      }
    }
    return sum;
  }, 0);
  
  console.log("Calculated total:", existingTotal);
  const expectedTotal = 220.00;
  const match = Math.abs(existingTotal - expectedTotal) < 0.01;
  
  console.log(`Expected: ${expectedTotal}, Got: ${existingTotal}, Match: ${match}`);
  
  return match;
}

// Test case 3: Test with string values (common from API)
function testWithStringValues() {
  console.log("\nTest 3: Testing with string values from API");
  
  const mockOrderWithStrings: MockOrder = {
    id: 9,
    orderNumber: "ORD-20260129-0001",
    customerId: 11437,
    orderItems: [
      {
        id: 21,
        orderId: 9,
        productId: "3", // String from API
        product: {
          id: 3,
          name: "test2",
          amount: "50.00",
        },
        count: "4", // String from API
        amountPerTub: "50.00",
        totalAmount: "220.00",
        postageServiceChargeId: "2",
        postageServiceCharge: {
          id: 2,
          name: "jay",
          amount: "20.00",
        },
      },
    ],
  };
  
  return testMapOrderItems(mockOrderWithStrings);
}

// Test case 4: Test input value formatting
function testInputValueFormatting() {
  console.log("\nTest 4: Testing input value formatting");
  
  const testCases = [
    { count: 4, expected: "4" },
    { count: 0, expected: "1" },
    { count: null, expected: "1" },
    { count: undefined, expected: "1" },
    { count: "4", expected: "4" },
  ];
  
  let allPassed = true;
  
  testCases.forEach((testCase) => {
    const countNum = Number(testCase.count);
    const value = testCase.count !== null && testCase.count !== undefined && !isNaN(countNum) && countNum > 0 
      ? String(testCase.count) 
      : "1";
    const passed = value === testCase.expected;
    console.log(`Count: ${testCase.count}, Expected: "${testCase.expected}", Got: "${value}", Pass: ${passed}`);
    if (!passed) allPassed = false;
  });
  
  return allPassed;
}

// Test case 5: Test order total input value
function testOrderTotalInputValue() {
  console.log("\nTest 5: Testing order total input value");
  
  const testCases = [
    { override: 220, calculated: 219.01, expected: "220" },
    { override: null, calculated: 219.01, expected: "219.01" },
    { override: 0, calculated: 219.01, expected: "219.01" },
    { override: null, calculated: 0, expected: "" },
  ];
  
  let allPassed = true;
  
  testCases.forEach((testCase) => {
    const value = testCase.override !== null && testCase.override > 0 
      ? String(testCase.override) 
      : testCase.calculated > 0 
        ? String(testCase.calculated) 
        : "";
    const passed = value === testCase.expected;
    console.log(`Override: ${testCase.override}, Calculated: ${testCase.calculated}, Expected: "${testCase.expected}", Got: "${value}", Pass: ${passed}`);
    if (!passed) allPassed = false;
  });
  
  return allPassed;
}

// Run all tests
function runAllTests() {
  console.log("=".repeat(60));
  console.log("ORDER MAPPING TESTS");
  console.log("=".repeat(60));
  
  const results = {
    test1: testMapOrderItems(mockApiResponse),
    test2: testCalculateOrderTotal(mockApiResponse),
    test3: testWithStringValues(),
    test4: testInputValueFormatting(),
    test5: testOrderTotalInputValue(),
  };
  
  console.log("\n" + "=".repeat(60));
  console.log("TEST RESULTS");
  console.log("=".repeat(60));
  console.log("Test 1 (Map Order Items):", results.test1 ? "✓ PASS" : "✗ FAIL");
  console.log("Test 2 (Calculate Order Total):", results.test2 ? "✓ PASS" : "✗ FAIL");
  console.log("Test 3 (String Values):", results.test3 ? "✓ PASS" : "✗ FAIL");
  console.log("Test 4 (Input Value Formatting):", results.test4 ? "✓ PASS" : "✗ FAIL");
  console.log("Test 5 (Order Total Input):", results.test5 ? "✓ PASS" : "✗ FAIL");
  
  const allPassed = Object.values(results).every(r => r === true);
  console.log("\nOverall:", allPassed ? "✓ ALL TESTS PASSED" : "✗ SOME TESTS FAILED");
  
  return results;
}

// Export for use
if (typeof module !== 'undefined' && module.exports) {
  module.exports = { runAllTests, testMapOrderItems, testCalculateOrderTotal };
}

// Run if executed directly
if (typeof window === 'undefined') {
  runAllTests();
}


