/**
 * Test script to verify the new plan validation behavior
 * 
 * This script tests the updated client methods and API behavior where:
 * - 404 is returned only when the plan doesn't exist
 * - 200 with empty arrays is returned when plan exists but has no products/work orders
 * 
 * Usage: node --experimental-strip-types test-plan-validation.ts
 */

import { HanaQueryClient } from './hana-query-client.ts';
import { NotFoundError } from './errors.ts';

// Configuration
const TEST_CONFIG = {
  baseUrl: 'http://192.168.15.28:3001',
  timeout: 30000,
  enableLogging: true,
  logLevel: 'info' as const
};

// Test plan IDs
const EXISTING_PLAN_ID = 5; // Adjust based on your data
const NON_EXISTENT_PLAN_ID = 99999;

async function testPlanValidation(): Promise<void> {
  console.log('🧪 Testing Plan Validation Behavior');
  console.log('=' .repeat(50));
  
  const client = new HanaQueryClient(TEST_CONFIG);
  
  // Test 1: Plan existence check
  console.log('\n📋 Test 1: Plan Existence Check');
  console.log('-'.repeat(30));
  
  try {
    const existsTrue = await client.planExists(EXISTING_PLAN_ID);
    console.log(`✅ Plan ${EXISTING_PLAN_ID} exists: ${existsTrue}`);
    
    const existsFalse = await client.planExists(NON_EXISTENT_PLAN_ID);
    console.log(`✅ Plan ${NON_EXISTENT_PLAN_ID} exists: ${existsFalse}`);
  } catch (error) {
    console.log(`❌ Plan existence check failed:`, error);
  }
  
  // Test 2: Products endpoint - existing plan
  console.log('\n📦 Test 2: Products for Existing Plan');
  console.log('-'.repeat(30));
  
  try {
    const result = await client.getPlanProducts(EXISTING_PLAN_ID);
    console.log(`✅ Products retrieved successfully:`);
    console.log(`   Plan ID: ${result.metadata.planId}`);
    console.log(`   Product count: ${result.metadata.count}`);
    console.log(`   Array length: ${result.data.products.length}`);
    
    if (result.data.products.length === 0) {
      console.log(`   📝 Note: Plan exists but has no products (this is normal)`);
    } else {
      console.log(`   📝 Sample product: ${result.data.products[0].itemcode}`);
    }
  } catch (error) {
    console.log(`❌ Products test failed:`, error);
  }
  
  // Test 3: Products endpoint - non-existent plan
  console.log('\n📦 Test 3: Products for Non-Existent Plan');
  console.log('-'.repeat(30));
  
  try {
    const result = await client.getPlanProducts(NON_EXISTENT_PLAN_ID);
    console.log(`❌ Should not reach here - expected 404 error`);
  } catch (error) {
    if (error instanceof NotFoundError) {
      console.log(`✅ Correctly received 404 for non-existent plan: ${error.message}`);
    } else {
      console.log(`❌ Unexpected error:`, error);
    }
  }
  
  // Test 4: Work orders endpoint - existing plan
  console.log('\n🏭 Test 4: Work Orders for Existing Plan');
  console.log('-'.repeat(30));
  
  try {
    const result = await client.getPlanWorkOrders(EXISTING_PLAN_ID);
    console.log(`✅ Work orders retrieved successfully:`);
    console.log(`   Plan ID: ${result.metadata.planId}`);
    console.log(`   Work order count: ${result.metadata.count}`);
    console.log(`   Array length: ${result.data.workOrders.length}`);
    
    if (result.data.workOrders.length === 0) {
      console.log(`   📝 Note: Plan exists but has no work orders (this is normal)`);
    } else {
      console.log(`   📝 Sample work order: ${result.data.workOrders[0].order_id}`);
    }
  } catch (error) {
    console.log(`❌ Work orders test failed:`, error);
  }
  
  // Test 5: Work orders endpoint - non-existent plan
  console.log('\n🏭 Test 5: Work Orders for Non-Existent Plan');
  console.log('-'.repeat(30));
  
  try {
    const result = await client.getPlanWorkOrders(NON_EXISTENT_PLAN_ID);
    console.log(`❌ Should not reach here - expected 404 error`);
  } catch (error) {
    if (error instanceof NotFoundError) {
      console.log(`✅ Correctly received 404 for non-existent plan: ${error.message}`);
    } else {
      console.log(`❌ Unexpected error:`, error);
    }
  }
  
  // Test 6: Safe methods - existing plan
  console.log('\n🛡️ Test 6: Safe Methods for Existing Plan');
  console.log('-'.repeat(30));
  
  try {
    const productsResult = await client.getPlanProductsSafe(EXISTING_PLAN_ID);
    console.log(`✅ Safe products method:`);
    console.log(`   Plan exists: ${productsResult.planExists}`);
    console.log(`   Product count: ${productsResult.products.length}`);
    
    const workOrdersResult = await client.getPlanWorkOrdersSafe(EXISTING_PLAN_ID);
    console.log(`✅ Safe work orders method:`);
    console.log(`   Plan exists: ${workOrdersResult.planExists}`);
    console.log(`   Work order count: ${workOrdersResult.workOrders.length}`);
  } catch (error) {
    console.log(`❌ Safe methods test failed:`, error);
  }
  
  // Test 7: Safe methods - non-existent plan
  console.log('\n🛡️ Test 7: Safe Methods for Non-Existent Plan');
  console.log('-'.repeat(30));
  
  try {
    const productsResult = await client.getPlanProductsSafe(NON_EXISTENT_PLAN_ID);
    console.log(`✅ Safe products method:`);
    console.log(`   Plan exists: ${productsResult.planExists}`);
    console.log(`   Product count: ${productsResult.products.length}`);
    
    const workOrdersResult = await client.getPlanWorkOrdersSafe(NON_EXISTENT_PLAN_ID);
    console.log(`✅ Safe work orders method:`);
    console.log(`   Plan exists: ${workOrdersResult.planExists}`);
    console.log(`   Work order count: ${workOrdersResult.workOrders.length}`);
  } catch (error) {
    console.log(`❌ Safe methods test failed:`, error);
  }
  
  console.log('\n✨ Plan validation tests completed!');
}

// Run tests
if (import.meta.url === `file://${process.argv[1]}`) {
  testPlanValidation().catch(error => {
    console.error('❌ Test execution failed:', error);
    process.exit(1);
  });
}

export { testPlanValidation };