import bcrypt from 'bcrypt';
import { prisma } from './db.js';

/**
 * Sync admin credentials from ADMIN_USERNAME / ADMIN_PASSWORD.
 * Required in production (Docker); optional in local dev (seed still creates admin).
 */
export async function ensureAdminFromEnv() {
  const username = String(process.env.ADMIN_USERNAME || '').trim();
  const password = String(process.env.ADMIN_PASSWORD || '');
  const required = process.env.NODE_ENV === 'production';

  if (!username || !password) {
    if (required) {
      throw new Error(
        'ADMIN_USERNAME and ADMIN_PASSWORD must be set in .env.prod for production',
      );
    }
    return;
  }

  if (password.length < 6) {
    throw new Error('ADMIN_PASSWORD must be at least 6 characters');
  }

  const passwordHash = await bcrypt.hash(password, 10);
  const existing = await prisma.user.findUnique({ where: { username } });

  if (existing) {
    await prisma.user.update({
      where: { id: existing.id },
      data: { passwordHash, role: 'admin' },
    });
  } else {
    const soleAdmin = await prisma.user.findFirst({ where: { role: 'admin' } });
    if (soleAdmin) {
      await prisma.user.update({
        where: { id: soleAdmin.id },
        data: { username, passwordHash },
      });
    } else {
      await prisma.user.create({
        data: {
          username,
          passwordHash,
          balance: 0,
          role: 'admin',
        },
      });
    }
  }

  console.log(`Admin account ready: ${username}`);
}
