const User = require('../models/User'); 
const Customer = require('../models/Customer'); 
const Role = require('../models/Role'); 
const Company = require('../models/Company');
const Branch = require('../models/Branch');
const bcrypt = require('bcryptjs'); // Use bcryptjs for password hashing

exports.createUser = async (req, res) => {
  try {
    const { companyName, branchName, username, email, password } = req.body;

    // Check if an image is uploaded
    const profileImagePath = req.file ? `/uploads/${req.file.filename}` : '';

    // Step 1: Check if the company already exists
    let company = await Company.findOne({ name: companyName });
    if (company) {
      // If company already exists, return an error message
      return res.status(400).json({ 
        error: 'A company with this name already exists. Please use a different company name.' 
      });
    }
    
    // Step 2: Create a new company with profile image URL
    company = new Company({
      name: companyName,
      profile_url: profileImagePath
    });
    await company.save();
    const companyId = company._id;

    // Step 3: Create a branch associated with the company
    const branch = new Branch({ name: branchName, companyId });
    await branch.save();
    const branchId = branch._id;

    // Hash the password
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);


    const roles = await Role.find()
    const adminRole = roles.find((role) => role.name === 'ADMIN');
   const roleId=adminRole._id;
    // Create a new user instance
    const user = new User({
      username,
      email,
      password: hashedPassword,
      companyId,
      branchId,
      roleId,
      passcode:'1111'
    });

    // Save the user to the database
    const savedUser = await user.save();


// create default suplier and customer
    const name="Walking";
    const balance=0;
    const customerType="customer";
   

    const customer = new Customer({
      companyId,
      name,
      customerType,
      balance,
     
    });

   

    await customer.save();
    


    // Return success response
    res.status(201).json({ success: true, user: savedUser });
  } catch (error) {
    console.error('Error creating user:', error);
    res.status(500).json({ error: error.message });
  }
};
