import { randomUUID } from 'node:crypto';
import { loadEnv } from '../config/env.js';
import { createDatabase } from '../db/database.js';
import { migrate } from '../db/migrations.js';
import { normalizeUsername } from '../domain/normalization.js';
import { generateTemporaryPassword, hashPassword } from '../services/passwords.js';
import { seedDatabase } from '../services/seed-data.js';
const username = process.argv[2];
const name = process.argv[3];
if (!username || !name) {
    console.error('کاربرد: npm run bootstrap:admin -- <username> "نام و نام خانوادگی"');
    process.exit(1);
}
const env = loadEnv();
const database = await createDatabase(env);
try {
    await migrate(database);
    await seedDatabase(database, false);
    const normalized = normalizeUsername(username);
    const exists = await database.query('SELECT id FROM users WHERE username_normalized = $1', [normalized]);
    if (exists.rowCount)
        throw new Error('این نام کاربری قبلاً ثبت شده است.');
    const refs = await database.query(`SELECT id AS branch_id FROM branches WHERE code = 'MAIN'`);
    const password = generateTemporaryPassword();
    await database.transaction(async (tx) => {
        const id = randomUUID();
        await tx.query(`INSERT INTO users(id, branch_id, name, username, username_normalized, password_hash)
       VALUES ($1,$2,$3,$4,$5,$6)`, [id, refs.rows[0].branch_id, name, username, normalized, await hashPassword(password)]);
        await tx.query(`INSERT INTO user_roles(user_id, role_id) SELECT $1, id FROM roles WHERE code = 'super_admin'`, [id]);
    });
    console.log(`مدیر کل ایجاد شد. نام کاربری: ${username}`);
    console.log(`رمز موقت (فقط یک‌بار): ${password}`);
    console.log('در اولین ورود، تغییر رمز اجباری است.');
}
finally {
    await database.close();
}
//# sourceMappingURL=bootstrap-admin.js.map