#!/usr/bin/env node
// backend/scripts/create-superadmin.js
// Run: node scripts/create-superadmin.js
import 'dotenv/config';
import bcrypt from 'bcryptjs';
import { pool } from '../src/utils/db.js';
import readline from 'readline';

const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
const ask = (q) => new Promise(res => rl.question(q, res));

async function main() {
  console.log('\n⚡ Content Machine — Create SuperAdmin\n');

  const email = process.env.SUPERADMIN_EMAIL || await ask('Email: ');
  const password = process.env.SUPERADMIN_PASSWORD || await ask('Password (min 8 chars): ');
  const name = await ask('Full name [Admin]: ') || 'Admin';

  if (password.length < 8) { console.error('Password too short'); process.exit(1); }

  const hash = await bcrypt.hash(password, 12);

  try {
    const { rows } = await pool.query(
      `INSERT INTO users (email, password_hash, full_name, role, status, email_verified, plan_id)
       VALUES ($1, $2, $3, 'superadmin', 'active', true, 'agency')
       ON CONFLICT (email) DO UPDATE SET role = 'superadmin', password_hash = $2
       RETURNING id, email, role`,
      [email, hash, name]
    );
    console.log('\n✅ SuperAdmin created:');
    console.log('   Email:', rows[0].email);
    console.log('   Role:', rows[0].role);
    console.log('   ID:', rows[0].id);
    console.log('\n→ Login at: ' + (process.env.APP_URL || 'https://yourdomain.com') + '/login\n');
  } catch (err) {
    console.error('Error:', err.message);
    process.exit(1);
  } finally {
    await pool.end();
    rl.close();
  }
}

main();
