const mysql = require('mysql2/promise');
const bcrypt = require('bcryptjs');
require('dotenv').config();

const dbConfig = {
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || '',
  database: process.env.DB_NAME || 'sts_v2'
};

async function createSchoolUser() {
  let connection;
  
  try {
    connection = await mysql.createConnection(dbConfig);
    console.log('Connected to database');

    // Create a school user with hashed password
    const hashedPassword = await bcrypt.hash('school123', 10);
    
    // Insert or update school user
    await connection.execute(`
      INSERT INTO users (id, username, email, password_hash, first_name, last_name, user_type, phone) VALUES 
      (100, 'schooladmin', 'school@test.com', ?, 'School', 'Admin', 'school', '555-0123')
      ON DUPLICATE KEY UPDATE 
      password_hash = VALUES(password_hash),
      first_name = VALUES(first_name),
      last_name = VALUES(last_name)
    `, [hashedPassword]);

    console.log('School user created/updated successfully!');
    console.log('Login credentials:');
    console.log('Email: school@test.com');
    console.log('Password: school123');

    // Update children to belong to this school user
    await connection.execute(`
      UPDATE children SET school_id = 100 WHERE school_id IS NULL OR school_id = 1
    `);

    // Update devices to belong to this school user  
    await connection.execute(`
      UPDATE devices SET school_id = 100 WHERE school_id IS NULL OR school_id = 1
    `);

    console.log('Updated children and devices to belong to school user');

  } catch (error) {
    console.error('Error creating school user:', error);
  } finally {
    if (connection) {
      await connection.end();
    }
  }
}

createSchoolUser();