const low      = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const path     = require('path');
const fs       = require('fs');
const bcrypt   = require('bcryptjs');
const { v4: uuidv4 } = require('uuid');

const dbDir = path.join(__dirname, '..', 'data');
if (!fs.existsSync(dbDir)) fs.mkdirSync(dbDir, { recursive: true });

function makeDb(filename, defaults) {
  const adapter = new FileSync(path.join(dbDir, filename));
  const db = low(adapter);
  db.defaults(defaults).write();
  return db;
}

const usersDb    = makeDb('users.json',    { users: [] });
const leaveDb    = makeDb('leave.json',    { requests: [] });
const reportsDb  = makeDb('reports.json',  { reports: [] });
const messagesDb = makeDb('messages.json', { threads: [] });
const salaryDb   = makeDb('salary.json',   { slips: [] });
const testsDb    = makeDb('tests.json',    { tests: [], results: [] });

// Seed default admin
function seedAdmin() {
  const existing = usersDb.get('users').find({ role: 'admin' }).value();
  if (!existing) {
    usersDb.get('users').push({
      id: uuidv4(),
      empId: 'ADMIN01',
      name: 'Admin',
      email: 'admin@auxis.com',
      phone: '',
      dept: 'Management',
      pos: 'System Administrator',
      role: 'admin',
      password: bcrypt.hashSync('admin@123', 10),
      doj: '',
      photo: null,
      createdAt: new Date().toISOString()
    }).write();
    console.log('✅ Admin seeded  → ID: ADMIN01  Password: admin@123');
  }
}
seedAdmin();

module.exports = { usersDb, leaveDb, reportsDb, messagesDb, salaryDb, testsDb, uuidv4 };
