import 'dotenv/config';
import bcrypt from 'bcryptjs';
import { db, pool } from './db.js';

const username = process.env.ADMIN_USERNAME || 'admin';
const password = process.env.ADMIN_PASSWORD;
if (!password || password.length < 12) {
  console.error('FATAL: ADMIN_PASSWORD env var not set or shorter than 12 chars.');
  process.exit(1);
}

const existing = await db.prepare('SELECT id FROM users WHERE username = ?').get(username);
if (existing) {
  console.log(`User "${username}" already exists (id=${existing.id}). Skipping.`);
  await pool.end();
  process.exit(0);
}

const hash = bcrypt.hashSync(password, 12);
const info = await db
  .prepare("INSERT INTO users (username, password_hash, role) VALUES (?, ?, 'owner') RETURNING id")
  .run(username, hash);

console.log(`Created admin user "${username}" (id=${info.lastInsertRowid}).`);
console.log(`Login with the password from your .env (ADMIN_PASSWORD).`);

await pool.end();
