/**
 * Create or update a Mailforge user for native auth (`MAILFORGE_NATIVE_AUTH`).
 *
 *   npx dotenv -c -- npx tsx --tsconfig tsconfig.json scripts/create-native-user.ts you@example.com 'secure-password'
 */

import { randomUUID } from 'node:crypto';
import { db } from '@/lib/db/client';
import { users } from '@/lib/db/schema';
import { getUserByEmail, setUserPasswordHash } from '@/lib/db/users-repo';
import { hashNativePassword } from '@/core/auth/password-native';

async function main(): Promise<void> {
  const [emailRaw, pwd] = process.argv.slice(2);
  if (!emailRaw || !pwd) {
    console.error('Usage: scripts/create-native-user.ts <email> <password>');
    process.exit(1);
  }
  const email = emailRaw.trim().toLowerCase();
  const hash = await hashNativePassword(pwd);
  const existing = getUserByEmail(email);
  if (existing) {
    setUserPasswordHash(existing.id, hash);
    console.log(`[create-native-user] Password updated for ${email}`);
    return;
  }
  db.insert(users)
    .values({
      id: randomUUID(),
      email,
      name: email,
      role: 'admin',
      passwordHash: hash,
    })
    .run();
  console.log(`[create-native-user] Created admin user ${email}`);
}

main().catch((e) => {
  console.error(e);
  process.exit(1);
});
