// Test script for Stations CRUD operations
// Run this in the browser console on the backoffice app

async function testStationsCRUD() {
  const API_URL = 'http://localhost:4000';
  const token = localStorage.getItem('auth_token');
  
  const headers = {
    'Content-Type': 'application/json',
    'Authorization': token ? `Bearer ${token}` : ''
  };

  console.log('🧪 Testing Stations CRUD Operations...\n');

  try {
    // 1. CREATE - Add a new station
    console.log('1️⃣ Testing CREATE Station...');
    const newStation = {
      code: 'TEST',
      name: 'Test Station',
      city: 'Test City',
      countryCode: 'ET',
      lat: '9.0320',
      lng: '38.7469',
      timezone: 'Africa/Addis_Ababa',
      isOperational: true
    };

    const createResponse = await fetch(`${API_URL}/stations`, {
      method: 'POST',
      headers,
      body: JSON.stringify(newStation)
    });

    if (!createResponse.ok) {
      throw new Error(`CREATE failed: ${createResponse.status} ${await createResponse.text()}`);
    }

    const createdStation = await createResponse.json();
    console.log('✅ Station created:', createdStation);
    const stationId = createdStation.id || createdStation.data?.id;

    if (!stationId) {
      throw new Error('No station ID returned from create');
    }

    // 2. READ - Get the created station
    console.log('\n2️⃣ Testing READ Station...');
    const readResponse = await fetch(`${API_URL}/stations/${stationId}`, {
      method: 'GET',
      headers
    });

    if (!readResponse.ok) {
      throw new Error(`READ failed: ${readResponse.status}`);
    }

    const readStation = await readResponse.json();
    console.log('✅ Station retrieved:', readStation);

    // 3. UPDATE - Modify the station
    console.log('\n3️⃣ Testing UPDATE Station...');
    const updateData = {
      name: 'Test Station Updated',
      city: 'Test City Updated',
      isOperational: false
    };

    const updateResponse = await fetch(`${API_URL}/stations/${stationId}`, {
      method: 'PATCH',
      headers,
      body: JSON.stringify(updateData)
    });

    if (!updateResponse.ok) {
      throw new Error(`UPDATE failed: ${updateResponse.status} ${await updateResponse.text()}`);
    }

    const updatedStation = await updateResponse.json();
    console.log('✅ Station updated:', updatedStation);

    // 4. LIST - Get all stations
    console.log('\n4️⃣ Testing LIST Stations...');
    const listResponse = await fetch(`${API_URL}/stations`, {
      method: 'GET',
      headers
    });

    if (!listResponse.ok) {
      throw new Error(`LIST failed: ${listResponse.status}`);
    }

    const stations = await listResponse.json();
    console.log('✅ Stations list retrieved:', stations);

    // 5. DELETE - Remove the test station
    console.log('\n5️⃣ Testing DELETE Station...');
    const deleteResponse = await fetch(`${API_URL}/stations/${stationId}`, {
      method: 'DELETE',
      headers
    });

    if (!deleteResponse.ok) {
      throw new Error(`DELETE failed: ${deleteResponse.status} ${await deleteResponse.text()}`);
    }

    console.log('✅ Station deleted successfully');

    // 6. Verify deletion
    console.log('\n6️⃣ Verifying deletion...');
    const verifyResponse = await fetch(`${API_URL}/stations/${stationId}`, {
      method: 'GET',
      headers
    });

    if (verifyResponse.status === 404) {
      console.log('✅ Station deletion verified (404 Not Found)');
    } else {
      console.warn('⚠️ Station might still exist');
    }

    console.log('\n🎉 All tests passed!');
    return { success: true, message: 'All CRUD operations working correctly' };

  } catch (error) {
    console.error('❌ Test failed:', error);
    return { success: false, error: error.message };
  }
}

// Run the test
testStationsCRUD();
