const axios = require('axios');

const API_BASE_URL = 'http://localhost:3000/api';

// Test credentials (using the sample users we found earlier)
const testCredentials = {
  email: 'admin@gmail.com', // Use email instead of login_id
  password: 'admin123' // Updated with correct password
};

let authToken = '';

// Test data for contact creation
const testContact = {
  name: 'Test User',
  email: `test.user.${Date.now()}@navy.mil`, // Use unique email with timestamp
  phone: '+8801717171717',
  mobile: '+8801717171718',
  unit_id: 1, // Will be updated with actual IDs
  department_id: 1, // Will be updated with actual IDs
  designation_id: 1 // Will be updated with actual IDs
};

async function login() {
  try {
    console.log('🔐 Logging in...');
    const response = await axios.post(`${API_BASE_URL}/auth/login`, testCredentials);
    
    if (response.data.status === 'success' && response.data.data?.token) {
      authToken = response.data.data.token;
      console.log('✅ Login successful');
      return true;
    } else {
      console.log('❌ Login failed:', response.data.message);
      return false;
    }
  } catch (error) {
    console.log('❌ Login error:', error.response?.data?.message || error.message);
    return false;
  }
}

async function testContactCreation() {
  console.log('🧪 Testing Contact Creation API...\n');

  try {
    // Step 0: Login first
    const loginSuccess = await login();
    if (!loginSuccess) {
      console.log('❌ Cannot proceed without authentication');
      return;
    }
    console.log('');

    // Set up axios defaults with auth token
    axios.defaults.headers.common['Authorization'] = `Bearer ${authToken}`;

    // First, let's get some sample data to use
    console.log('1️⃣ Getting sample organizational data...');
    
    // Get units
    const unitsResponse = await axios.get(`${API_BASE_URL}/units`);
    console.log('Units available:', unitsResponse.data?.data?.units?.length || 0);
    
    // Get departments
    const departmentsResponse = await axios.get(`${API_BASE_URL}/departments`);
    console.log('Departments available:', departmentsResponse.data?.data?.departments?.length || 0);
    
    // Get designations
    const designationsResponse = await axios.get(`${API_BASE_URL}/organizational/designations`);
    console.log('Designations available:', designationsResponse.data?.data?.designations?.length || 0);
    
    // Update test data with actual IDs if available
    if (unitsResponse.data?.data?.units?.length > 0) {
      testContact.unit_id = 1; // Use Naval Headquarters
    }
    if (departmentsResponse.data?.data?.departments?.length > 0) {
      testContact.department_id = 8; // Use ACNS department which belongs to Naval Headquarters
    }
    if (designationsResponse.data?.data?.designations?.length > 0) {
      testContact.designation_id = designationsResponse.data.data.designations[0].id;
    } else {
      testContact.designation_id = 1; // Use default designation ID
    }
    
    console.log('Using test data:', testContact);
    console.log('');

    // Test 2: Create a new contact
    console.log('2️⃣ Testing POST /contacts (Create contact)...');
    const createResponse = await axios.post(`${API_BASE_URL}/contacts`, testContact);
    console.log('✅ Success:', createResponse.data);
    const createdContactId = createResponse.data.data.contact.id;
    console.log('');

    // Test 3: Get the created contact
    console.log('3️⃣ Testing GET /contacts/:id...');
    const getContactResponse = await axios.get(`${API_BASE_URL}/contacts/${createdContactId}`);
    console.log('✅ Success:', getContactResponse.data);
    console.log('');

    // Test 4: Update the contact
    console.log('4️⃣ Testing PUT /contacts/:id (Update contact)...');
    const updateData = {
      ...testContact,
      name: 'Updated Test User',
      mobile: '+8801717171719'
    };
    const updateResponse = await axios.put(`${API_BASE_URL}/contacts/${createdContactId}`, updateData);
    console.log('✅ Success:', updateResponse.data);
    console.log('');

    // Test 5: Delete the contact
    console.log('5️⃣ Testing DELETE /contacts/:id...');
    const deleteResponse = await axios.delete(`${API_BASE_URL}/contacts/${createdContactId}`);
    console.log('✅ Success:', deleteResponse.data);
    console.log('');

    console.log('🎉 All contact creation tests passed! Contact Management API is working correctly.');

  } catch (error) {
    console.error('❌ Test failed:', error.response?.data || error.message);
    if (error.response?.data?.errors) {
      console.error('Validation errors:', error.response.data.errors);
    }
  }
}

// Run the test
testContactCreation();
