const bcrypt = require('bcryptjs');
const {pool} = require('../src/config/db');

async function seedOwner() {
  const name = process.env.OWNER_NAME || 'Owner';
  const username = process.env.OWNER_USERNAME || 'owner';
  const password = process.env.OWNER_PASSWORD || 'Owner@123';
  const mobile = process.env.OWNER_MOBILE || null;
  const email = process.env.OWNER_EMAIL || null;

  const [shops] = await pool.execute('SELECT id FROM shops ORDER BY id LIMIT 1');
  const [roles] = await pool.execute("SELECT id FROM roles WHERE role_key = 'owner' LIMIT 1");

  if (!shops.length || !roles.length) {
    throw new Error('Run backend/database.sql before seeding owner user.');
  }

  const passwordHash = await bcrypt.hash(password, 12);
  await pool.execute(
    `INSERT INTO users (shop_id, role_id, name, username, password_hash, mobile, email, status)
     VALUES (?, ?, ?, ?, ?, ?, ?, 'Active')
     ON DUPLICATE KEY UPDATE
       name = VALUES(name),
       password_hash = VALUES(password_hash),
       mobile = VALUES(mobile),
       email = VALUES(email),
       status = 'Active'`,
    [shops[0].id, roles[0].id, name, username, passwordHash, mobile, email],
  );

  console.log(`Owner user ready. username=${username} password=${password}`);
}

seedOwner()
  .catch(error => {
    console.error(error);
    process.exitCode = 1;
  })
  .finally(() => pool.end());
