const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const User = require('../models/User');

const seedUsers = async () => {
  const defaults = [
    { name: 'Library Admin', username: 'admin', password: 'admin123', role: 'admin' },
    { name: 'Library Staff', username: 'librarian', password: 'lib123', role: 'librarian' },
  ];

  for (const item of defaults) {
    const exists = await User.findOne({ username: item.username });
    if (!exists) {
      const hashedPassword = await bcrypt.hash(item.password, 10);
      await User.create({
        name: item.name,
        username: item.username,
        password: hashedPassword,
        role: item.role,
      });
      console.log(`Seeded user: ${item.username}`);
    }
  }
};

const connectDB = async () => {
  try { 
    await mongoose.connect('mongodb://localhost:27017/library-lms');
    console.log('MongoDB connected');
    await seedUsers();
  } catch (error) {
    console.error('MongoDB connection error:', error);
  }
};

module.exports = connectDB;
