// Promotes (or demotes) a user's role. Usage:
//   node scripts/set-owner.mjs owner@example.com owner
//   node scripts/set-owner.mjs owner@example.com rider

import pg from "pg";
import { readFileSync } from "fs";

const [email, role = "owner"] = process.argv.slice(2);

if (!email) {
  console.error("Usage: node scripts/set-owner.mjs <email> [role]");
  console.error("Roles: owner | driver | rider");
  process.exit(1);
}

const env = readFileSync(new URL("../.env", import.meta.url), "utf8");
const databaseUrl = env
  .split("\n")
  .find((l) => l.startsWith("DATABASE_URL="))
  ?.split("=")
  .slice(1)
  .join("=")
  .trim()
  .replace(/^"|"$/g, "");

const pool = new pg.Pool({ connectionString: databaseUrl });

try {
  const { rows } = await pool.query(
    `UPDATE users SET email_verified = TRUE, role = $2 WHERE email = $1 RETURNING id, email, role`,
    [email.toLowerCase(), role],
  );

  if (!rows[0]) {
    console.error(`No user found with email ${email}`);
    process.exit(1);
  }

  console.log(
    `Updated ${rows[0].email}: role=${rows[0].role}, email_verified=true`,
  );
} finally {
  await pool.end();
}
