/**
 * scripts/create-admin.js
 * ─────────────────────────────────────────────────────────────
 * Creates or resets an admin user in the cPanel MySQL database.
 * Admin authentication uses MySQL — NOT SQLite.
 *
 * Usage (requires SSH or terminal access):
 *   node scripts/create-admin.js <username> <password>
 *
 * Examples:
 *   node scripts/create-admin.js tony MySecurePass@2024   # creates user
 *   node scripts/create-admin.js tony NewPass@456         # resets password
 *
 * Requirements:
 *   - MySQL environment variables must be set (DB_HOST, DB_USER, DB_PASS,
 *     DB_NAME, DB_PORT) — either in .env or in cPanel environment variables.
 *   - The admin_users table must already exist in the MySQL database.
 *     Run the CREATE TABLE SQL in phpMyAdmin if it does not.
 *
 * No terminal access?
 *   Use the browser-based bootstrap route instead:
 *   https://yourdomain.com/admin/bootstrap?token=YOUR_ADMIN_SETUP_TOKEN
 * ─────────────────────────────────────────────────────────────
 */

'use strict';

require('dotenv').config();

const mysqldb = require('../lib/mysqldb');

async function main() {
  const [,, username, password] = process.argv;

  if (!username || !password) {
    console.error('Usage: node scripts/create-admin.js <username> <password>');
    console.error('Example: node scripts/create-admin.js tony MySecurePass@2024');
    process.exit(1);
  }

  if (password.length < 8) {
    console.error('Error: Password must be at least 8 characters.');
    process.exit(1);
  }

  const normalizedUsername = username.trim().toLowerCase();

  try {
    // Confirm MySQL is reachable before attempting anything
    await mysqldb.connect();

    const existing = await mysqldb.getAdminUserByUsername(normalizedUsername);

    if (existing) {
      // Reset password for an existing user
      await mysqldb.changeAdminPassword(existing.id, password);
      console.log(`\n✓ Password updated in MySQL for admin: "${normalizedUsername}"`);
    } else {
      // Create a new admin user (addAdminUser hashes the password internally)
      await mysqldb.addAdminUser(normalizedUsername, normalizedUsername, password, 'superadmin');
      console.log(`\n✓ Admin user created in MySQL:`);
      console.log(`  Username: ${normalizedUsername}`);
    }

    console.log(`\nLog in at: /admin/login`);
    console.log('Done.\n');
    process.exit(0);

  } catch (err) {
    console.error('\nError:', err.message);
    console.error('Make sure DB_HOST, DB_USER, DB_PASS, DB_NAME are set correctly.');
    process.exit(1);
  }
}

main();
