/**
 * Test Script: Production Availability Check and Confirmation
 * Tests the availability check and production confirmation for production order 18
 * 
 * Usage: node server/scripts/test-production-availability.js
 */

const axios = require('axios');

// Configuration
const BASE_URL = process.env.API_URL || 'http://localhost:4000';
const API_BASE = `${BASE_URL}/api`;

// Test credentials (adjust as needed)
const TEST_USERNAME = process.env.TEST_USERNAME || 'admin';
const TEST_PASSWORD = process.env.TEST_PASSWORD || 'admin123';

let authToken = null;

/**
 * Login and get auth token
 */
async function login() {
  try {
    console.log('\n=== Logging in ===');
    const response = await axios.post(`${API_BASE}/auth/login`, {
      username: TEST_USERNAME,
      password: TEST_PASSWORD,
    });

    if (response.data.success && response.data.data.token) {
      authToken = response.data.data.token;
      console.log('✓ Login successful');
      return true;
    } else {
      console.error('✗ Login failed:', response.data);
      return false;
    }
  } catch (error) {
    console.error('✗ Login error:', error.response?.data || error.message);
    return false;
  }
}

/**
 * Get product by name/SKU
 */
async function getProduct(searchTerm) {
  try {
    console.log(`\n=== Searching for product: ${searchTerm} ===`);
    const response = await axios.get(`${API_BASE}/products`, {
      headers: { Authorization: `Bearer ${authToken}` },
      params: { search: searchTerm, limit: 10 },
    });

    const products = response.data?.data?.products || response.data?.data || [];
    const product = products.find(p => 
      p.name?.includes(searchTerm) || 
      p.sku?.includes(searchTerm)
    );

    if (product) {
      console.log(`✓ Found product: ${product.name} (ID: ${product.id}, SKU: ${product.sku})`);
      console.log(`  - Type: ${product.product_type}`);
      console.log(`  - Track by dimensions: ${product.track_by_dimensions}`);
      console.log(`  - Unit: ${product.unit_of_measure}`);
      return product;
    } else {
      console.log('✗ Product not found');
      return null;
    }
  } catch (error) {
    console.error('✗ Error fetching product:', error.response?.data || error.message);
    return null;
  }
}

/**
 * Get production order details
 */
async function getProductionOrder(orderId) {
  try {
    console.log(`\n=== Fetching Production Order ${orderId} ===`);
    const response = await axios.get(`${API_BASE}/production/orders/${orderId}`, {
      headers: { Authorization: `Bearer ${authToken}` },
    });

    if (response.data.success && response.data.data.productionOrder) {
      const order = response.data.data.productionOrder;
      console.log(`✓ Production Order ${orderId}:`);
      console.log(`  - Status: ${order.status}`);
      console.log(`  - Quantity: ${order.quantity}`);
      console.log(`  - Variant ID: ${order.fg_variant_id}`);
      if (order.bom && order.bom.items) {
        console.log(`  - BOM Items: ${order.bom.items.length}`);
        order.bom.items.forEach((item, idx) => {
          console.log(`    ${idx + 1}. ${item.rawMaterial?.name || 'Unknown'} (${item.use_dimensions ? 'Dimension-Based' : 'Quantity-Based'})`);
        });
      }
      return order;
    } else {
      console.log('✗ Production order not found');
      return null;
    }
  } catch (error) {
    console.error('✗ Error fetching production order:', error.response?.data || error.message);
    return null;
  }
}

/**
 * Check availability for production order
 */
async function checkAvailability(orderId) {
  try {
    console.log(`\n=== Checking Availability for Production Order ${orderId} ===`);
    const response = await axios.get(
      `${API_BASE}/production/orders/${orderId}/check-availability`,
      {
        headers: { Authorization: `Bearer ${authToken}` },
      }
    );

    if (response.data.success) {
      const data = response.data.data;
      console.log(`✓ Availability Check Results:`);
      console.log(`  - All Available: ${data.all_available}`);
      console.log(`  - Requested Quantity: ${data.requested_quantity}`);
      console.log(`  - Max Producible Units: ${data.max_producible_units || 'N/A'}`);
      console.log(`  - Items Checked: ${data.items.length}`);

      console.log(`\n  Item Details:`);
      data.items.forEach((item, idx) => {
        console.log(`\n    Item ${idx + 1}: ${item.rm_product_name}`);
        console.log(`      - Type: ${item.use_dimensions ? 'Dimension-Based' : 'Quantity-Based'}`);
        console.log(`      - Available: ${item.available}`);
        
        if (item.use_dimensions) {
          console.log(`      - Required: ${item.total_area_required} ${item.dimensions?.unit || 'm'}²`);
          console.log(`      - Available Area: ${item.available_area} ${item.dimensions?.unit || 'm'}²`);
          console.log(`      - Area Per Unit: ${item.area_per_unit} ${item.dimensions?.unit || 'm'}²`);
          console.log(`      - Shortfall: ${item.shortfall || 0} ${item.dimensions?.unit || 'm'}²`);
          console.log(`      - Dimensions: ${item.dimensions?.length} × ${item.dimensions?.width} ${item.dimensions?.unit}`);
          console.log(`      - Max Producible: ${item.max_producible_units || 0} units`);
        } else {
          console.log(`      - Required: ${item.required_quantity}`);
          console.log(`      - Available: ${item.current_quantity}`);
          console.log(`      - Per Unit: ${item.quantity_per_unit}`);
          console.log(`      - Shortfall: ${item.shortfall || 0}`);
          console.log(`      - Max Producible: ${item.max_producible_units || 0} units`);
        }
        
        if (item.error) {
          console.log(`      - ERROR: ${item.error}`);
        }
      });

      return data;
    } else {
      console.log('✗ Availability check failed:', response.data.message);
      return null;
    }
  } catch (error) {
    console.error('✗ Error checking availability:', error.response?.data || error.message);
    if (error.response?.data) {
      console.error('  Response:', JSON.stringify(error.response.data, null, 2));
    }
    return null;
  }
}

/**
 * Confirm production order
 */
async function confirmProduction(orderId, userId = 1) {
  try {
    console.log(`\n=== Confirming Production Order ${orderId} ===`);
    const response = await axios.post(
      `${API_BASE}/production/orders/${orderId}/confirm`,
      {
        generate_uid: true,
      },
      {
        headers: { Authorization: `Bearer ${authToken}` },
      }
    );

    if (response.data.success) {
      console.log(`✓ Production Order ${orderId} confirmed successfully`);
      console.log(`  Response:`, JSON.stringify(response.data.data, null, 2));
      return response.data.data;
    } else {
      console.log('✗ Confirmation failed:', response.data.message);
      if (response.data.errors) {
        console.log('  Errors:', JSON.stringify(response.data.errors, null, 2));
      }
      return null;
    }
  } catch (error) {
    console.error('✗ Error confirming production:', error.response?.data || error.message);
    if (error.response?.data) {
      console.error('  Response:', JSON.stringify(error.response.data, null, 2));
    }
    return null;
  }
}

/**
 * Main test function
 */
async function runTests() {
  console.log('========================================');
  console.log('Production Availability Test Script');
  console.log('========================================');

  // Login
  const loggedIn = await login();
  if (!loggedIn) {
    console.error('\n✗ Cannot proceed without authentication');
    process.exit(1);
  }

  // Test 1: Find the product
  const product = await getProduct('Test Cotton Fabric 1768376270872');
  if (!product) {
    console.error('\n✗ Cannot proceed without product');
    process.exit(1);
  }

  // Test 2: Get production order 18
  const order = await getProductionOrder(18);
  if (!order) {
    console.error('\n✗ Cannot proceed without production order');
    process.exit(1);
  }

  // Test 3: Check availability
  const availability = await checkAvailability(18);
  if (!availability) {
    console.error('\n✗ Availability check failed');
    process.exit(1);
  }

  // Test 4: Confirm production (if available)
  if (availability.all_available) {
    console.log('\n=== All materials available, attempting confirmation ===');
    const confirmation = await confirmProduction(18);
    if (!confirmation) {
      console.error('\n✗ Production confirmation failed');
      process.exit(1);
    }
  } else {
    console.log('\n⚠️  Not all materials are available. Skipping confirmation.');
    console.log('   Review the availability results above to identify missing materials.');
  }

  console.log('\n========================================');
  console.log('Test completed');
  console.log('========================================');
}

// Run tests
runTests().catch((error) => {
  console.error('\n✗ Unexpected error:', error);
  process.exit(1);
});
