/**
 * Upsert MYSQL_* into backend/.env without printing secrets.
 * Password passed via env UPSERT_MYSQL_PASSWORD to avoid shell $ expansion.
 */
import fs from "fs";
import path from "path";

const envPath = path.join(process.cwd(), ".env");
if (!fs.existsSync(envPath)) throw new Error(".env missing");

const password = process.env.UPSERT_MYSQL_PASSWORD;
if (password === undefined) throw new Error("UPSERT_MYSQL_PASSWORD required");

const host = process.env.UPSERT_MYSQL_HOST || "127.0.0.1";
const port = process.env.UPSERT_MYSQL_PORT || "3306";
const user = process.env.UPSERT_MYSQL_USER || "root";
const database = process.env.UPSERT_MYSQL_DATABASE || "safar_libya";

let text = fs.readFileSync(envPath, "utf8");
const set = (key: string, value: string) => {
  // Always double-quote so $ and Unicode are preserved literally
  const line = `${key}="${value.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
  const re = new RegExp(`^${key}=.*$`, "m");
  if (re.test(text)) text = text.replace(re, line);
  else text = text.replace(/\s*$/, `\n${line}\n`);
};

set("MYSQL_HOST", host);
set("MYSQL_PORT", port);
set("MYSQL_USER", user);
set("MYSQL_PASSWORD", password);
set("MYSQL_DATABASE", database);
if (!/^ACTIVE_DATABASE=/m.test(text)) {
  text = text.replace(/\s*$/, `\nACTIVE_DATABASE="mongodb"\n`);
}

fs.writeFileSync(envPath, text, "utf8");
console.log("Updated MYSQL_* and ACTIVE_DATABASE in .env (password not printed)");
console.log(`MYSQL_HOST=${host}`);
console.log(`MYSQL_PORT=${port}`);
console.log(`MYSQL_USER=${user}`);
console.log(`MYSQL_DATABASE=${database}`);
console.log(`MYSQL_PASSWORD_LENGTH=${password.length}`);
