import 'dotenv/config';
import postgres from 'postgres';

const user = process.env.POSTGRES_USER || 'postgres';
const password = process.env.POSTGRES_PASSWORD || '';
const host = process.env.POSTGRES_HOST || 'localhost';
const port = process.env.POSTGRES_PORT || '5432';
const database = process.env.POSTGRES_DB || 'scriba';
const connectionString = password
  ? `postgres://${user}:${password}@${host}:${port}/${database}`
  : `postgres://${user}@${host}:${port}/${database}`;

const sql = postgres(connectionString);

async function main() {
  const email = process.argv[2]?.trim().toLowerCase();

  if (!email) {
    console.error('Usage: npm run user:make-admin -- <email>');
    process.exitCode = 1;
    await sql.end();
    return;
  }

  const existing = await sql`
    select id, email, role, tier
    from "user"
    where lower(email) = ${email}
    limit 1
  `;

  if (existing.length === 0) {
    console.error(`User not found: ${email}`);
    process.exitCode = 1;
    await sql.end();
    return;
  }

  const updated = await sql`
    update "user"
    set role = 'admin', updated_at = now()
    where lower(email) = ${email}
    returning id, email, role, tier
  `;

  console.log('User promoted to admin:');
  console.log(JSON.stringify(updated[0], null, 2));
  await sql.end();
}

main().catch(async (error) => {
  console.error('Failed to promote user to admin:', error);
  process.exitCode = 1;
  await sql.end();
});
