#!/usr/bin/env node
/**
 * seed-admin.js
 * CLI-only superadmin bootstrap.
 * Usage:  node seed-admin.js [--email=...] [--password=...] [--name=...]
 *
 * Reads SEED_ADMIN_* env vars as defaults. NEVER expose this as a route.
 */

'use strict';

require('dotenv').config();
const db   = require('./config/db');
const User = require('./models/user');
const Audit = require('./models/auditLog');

function arg(name) {
  const m = process.argv.find(a => a.startsWith(`--${name}=`));
  return m ? m.split('=', 2)[1] : null;
}

const email    = (arg('email')    || process.env.SEED_ADMIN_EMAIL    || '').toLowerCase().trim();
const password = (arg('password') || process.env.SEED_ADMIN_PASSWORD || '');
const name     = (arg('name')     || process.env.SEED_ADMIN_NAME     || 'Platform Admin');

if (!email || !password) {
  console.error('Usage: node seed-admin.js --email=you@example.com --password=StrongPassword!1 --name="Your Name"');
  process.exit(1);
}
if (password.length < 10 || !/[0-9]/.test(password) || !/[^A-Za-z0-9]/.test(password)) {
  console.error('Password must be ≥10 chars, include a number and a symbol.');
  process.exit(1);
}

db.init();

const existing = User.getByEmail(email);
if (existing) {
  if (existing.role === 'superadmin') {
    console.log(`[seed] ${email} is already a superadmin. Updating password.`);
    User.setPassword(existing.id, password);
    User.update(existing.id, { name });
    process.exit(0);
  } else {
    console.error(`[seed] ${email} exists but is not a superadmin. Promote manually via SQL if intentional.`);
    process.exit(2);
  }
}

const u = User.create({ email, password, name, role: 'superadmin', plan: 'agency' });
// verify email and clear quota
const { db: rawDb } = require('./config/db');
rawDb.prepare('UPDATE users SET email_verified = 1, verify_token = NULL, verify_expires = NULL WHERE id = ?').run(u.id);
Audit.log(u, 'seed.admin.create', `user:${u.id}`);
console.log(`[seed] superadmin created: ${email}`);
console.log(`[seed] user_id = ${u.id}`);
console.log('[seed] You can now sign in and visit /admin/ to manage the platform.');
process.exit(0);
