import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';

const db = new PrismaClient();

async function main() {
  const email = process.env.SEED_USER_EMAIL;
  const password = process.env.SEED_USER_PASSWORD;
  const name = process.env.SEED_USER_NAME || 'Admin';

  if (!email || !password) {
    console.warn('Skipping seed: SEED_USER_EMAIL and SEED_USER_PASSWORD are required. Auth-dependent E2E tests will skip or fail.');
    process.exit(0);
  }

  const passwordHash = await bcrypt.hash(password, 12);

  const user = await db.user.upsert({
    where: { email },
    update: {
      name,
      passwordHash,
      emailVerified: new Date(),
    },
    create: {
      email,
      name,
      passwordHash,
      emailVerified: new Date(),
      plan: 'free',
    },
  });

  console.log(`Seeded user: ${user.id} (${user.email}) plan=${user.plan}`);
}

main()
  .catch((e) => {
    console.error('Seed failed:', e);
    process.exit(1);
  })
  .finally(() => db.$disconnect());
