import 'dotenv/config';
import bcrypt from 'bcryptjs';
import { db } from './index.js';
import { users } from './schema.js';
import { eq } from 'drizzle-orm';

async function seed() {
  const email = process.env.ADMIN_EMAIL || 'admin@nfbs.local';
  const password = process.env.ADMIN_PASSWORD || 'admin123';
  const nama = process.env.ADMIN_NAME || 'Administrator';

  const existing = await db.select().from(users).where(eq(users.email, email)).limit(1);

  if (existing.length > 0) {
    console.log(`ℹ️  Admin '${email}' sudah ada, skip seed.`);
    process.exit(0);
  }

  const passwordHash = await bcrypt.hash(password, 10);
  await db.insert(users).values({ nama, email, passwordHash, role: 'admin' });

  console.log(`✅ Admin dibuat: ${email} / ${password}`);
  console.log('⚠️  Ubah password setelah login pertama (saat ini reset password manual via DB).');
  process.exit(0);
}

seed().catch((err) => {
  console.error('❌ Seed gagal:', err);
  process.exit(1);
});
