import {randomBytes,randomUUID,scrypt as sc} from "node:crypto";
import {promisify} from "node:util";
import pg from "pg";
const username=(process.env.ADMIN_USERNAME||"admin").trim().toLowerCase(),password=process.env.ADMIN_PASSWORD||"",fullName=process.env.ADMIN_FULL_NAME||"مدیر کل سامانه";if(!/^[a-z0-9._-]{3,32}$/.test(username)||password.length<12)throw Error("Set a valid ADMIN_USERNAME and ADMIN_PASSWORD with at least 12 characters");const salt=randomBytes(16).toString("hex"),key=await promisify(sc)(password,salt,64),hash=`scrypt:${salt}:${Buffer.from(key).toString("hex")}`;const cfg=process.env.DATABASE_URL?{connectionString:process.env.DATABASE_URL}:{host:process.env.PGHOST||"127.0.0.1",port:Number(process.env.PGPORT||5432),database:process.env.PGDATABASE,user:process.env.PGUSER,password:process.env.PGPASSWORD};const pool=new pg.Pool({...cfg,max:1});try{await pool.query("insert into users (id,username,password_hash,full_name,role,is_active,must_change_password) values ($1,$2,$3,$4,'general_manager',true,true) on conflict (username) do update set password_hash=excluded.password_hash,full_name=excluded.full_name,role='general_manager',is_active=true",[randomUUID(),username,hash,fullName]);console.log(`General manager '${username}' is ready.`)}finally{await pool.end()}
