#!/usr/bin/env node

/**
 * Create Test Users Script
 *
 * Seeds the alice + bob test-user fixtures used by the manual QA flows
 * in TESTING_GUIDE.md. Both users share a single password supplied via
 * the TEST_USERS_PASSWORD environment variable — this is a test-fixture
 * helper, not a prod auth surface, so per-user env vars would be
 * unnecessary sprawl.
 *
 * Required env (in .env.local):
 *   POSTGRES_URL         — Neon connection string
 *   TEST_USERS_PASSWORD  — strong password applied to every test user
 *                          (generate with `openssl rand -base64 24`)
 *
 * Mirrors the post-`drop-public-setup` shape of `setup-neon-db.js`
 * (commit b63b509) and the post-`fix-reset-db-script` shape of
 * `reset-db.js` (commit 3ab9bf8) — same ESM imports, same fail-loud
 * env-var check, same no-password-echo convention. Convoy:
 * `purge-weak-creds-from-helpers` (2026-05-26).
 */

import { config } from 'dotenv';
import { sql } from '@vercel/postgres';
import bcrypt from 'bcryptjs';

config({ path: '.env.local' });

async function createTestUsers() {
  const testUsersPassword = process.env.TEST_USERS_PASSWORD;
  if (!testUsersPassword || !testUsersPassword.trim()) {
    console.error(
      '❌ TEST_USERS_PASSWORD environment variable is not set.\n' +
        '\n' +
        '   Set it in .env.local before running `node scripts/create-test-users.js`.\n' +
        '   Generate a strong password with: openssl rand -base64 24\n' +
        '   See README.md → "First-time admin setup" for the env-var pattern.\n'
    );
    process.exit(1);
  }

  try {
    console.log('👥 Creating test users...\n');

    const hashedPassword = await bcrypt.hash(testUsersPassword, 12);

    await sql`
      INSERT INTO users (email, password, role)
      VALUES ('alice@deckhearth.com', ${hashedPassword}, 'user')
      ON CONFLICT (email) DO NOTHING
    `;
    console.log('✅ Created Alice (alice@deckhearth.com)');

    await sql`
      INSERT INTO users (email, password, role)
      VALUES ('bob@deckhearth.com', ${hashedPassword}, 'user')
      ON CONFLICT (email) DO NOTHING
    `;
    console.log('✅ Created Bob (bob@deckhearth.com)');

    console.log('\n🎉 Test users created successfully!');
    console.log('\n👥 Available Test Accounts (passwords from TEST_USERS_PASSWORD):');
    console.log('   1. admin@deckhearth.com (Admin — seeded by setup-neon-db.js)');
    console.log('   2. alice@deckhearth.com (User)');
    console.log('   3. bob@deckhearth.com (User)');

  } catch (error) {
    console.error('❌ Failed to create test users:', error.message);
    process.exit(1);
  }
}

createTestUsers();
