const http = require('http');
require('dotenv').config();

const API_BASE_URL = process.env.API_BASE_URL || 'http://localhost:3002';

function testAddStudentWithParent() {
  console.log('Testing add student with parent...');
  
  const studentData = {
    first_name: 'Test',
    last_name: 'Student',
    standard: '5th',
    division: 'A',
    roll_number: '101',
    device_id: '',
    parent_mobile_1: '9876543210',
    parent_mobile_2: '',
    parent_data: {
      email: 'testparent@example.com',
      first_name: 'Test',
      last_name: 'Parent',
      phone: '9876543210',
      address: '123 Test Street',
      password: 'parent123',
      exists: false
    }
  };
  
  const postData = JSON.stringify(studentData);
  
  const options = {
    hostname: 'localhost',
    port: 3002,
    path: '/api/school/students-with-parent',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    }
  };
  
  const req = http.request(options, (res) => {
    let data = '';
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('Response status:', res.statusCode);
      console.log('Response:', data);
      
      if (res.statusCode === 200) {
        console.log('✓ Student with parent added successfully!');
        testParentLogin();
      } else {
        console.log('✗ Failed to add student with parent');
      }
    });
  });
  
  req.on('error', (error) => {
    console.error('Request error:', error.message);
  });
  
  req.write(postData);
  req.end();
}

function testParentLogin() {
  console.log('\nTesting parent login...');
  
  const loginData = {
    email: 'testparent@example.com',
    password: Buffer.from('parent123').toString('base64')
  };
  
  const postData = JSON.stringify(loginData);
  
  const options = {
    hostname: 'localhost',
    port: 3002,
    path: '/api/auth/parent/login',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(postData)
    }
  };
  
  const req = http.request(options, (res) => {
    let data = '';
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('Login response status:', res.statusCode);
      console.log('Login response:', data);
      
      if (res.statusCode === 200) {
        const response = JSON.parse(data);
        console.log('✓ Parent login successful!');
        console.log('Parent:', response.user.name);
        testGetChildren(response.user.email);
      } else {
        console.log('✗ Parent login failed');
      }
    });
  });
  
  req.on('error', (error) => {
    console.error('Login error:', error.message);
  });
  
  req.write(postData);
  req.end();
}

function testGetChildren(parentEmail) {
  console.log('\nTesting get children for parent...');
  
  const options = {
    hostname: 'localhost',
    port: 3002,
    path: `/api/parent/children-test?parent_email=${encodeURIComponent(parentEmail)}`,
    method: 'GET'
  };
  
  const req = http.request(options, (res) => {
    let data = '';
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      console.log('Children response status:', res.statusCode);
      console.log('Children response:', data);
      
      if (res.statusCode === 200) {
        const children = JSON.parse(data);
        console.log('✓ Children retrieved successfully!');
        console.log(`Found ${children.length} children for parent`);
        children.forEach(child => {
          console.log(`- ${child.first_name} ${child.last_name} (${child.standard}-${child.division})`);
        });
      } else {
        console.log('✗ Failed to get children');
      }
    });
  });
  
  req.on('error', (error) => {
    console.error('Children request error:', error.message);
  });
  
  req.end();
}

testAddStudentWithParent();