const User = require('../models/User');
const bcrypt = require('bcryptjs');
const saltRounds = 10; 

exports.getUsers = async (req, res) => {
  try {
    const user = await User.findAll();
    res.status(200).json(user);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

exports.getUsersByID = async (req, res) => {
  try {
    const { id } = req.params;
    const user = await User.findByPk(id);
    if (user) {
        res.status(200).json({ actionStatus: 'Success', data: user });
    } else {
        res.status(404).json({ actionStatus: 'Failed', message: 'Product not found' });
    }
} catch (error) {
    res.status(500).json({ actionStatus: 'Failed', message: error.message });
}
};


exports.createUser = async (req, res) => {
  try {
    const { user_id, first_name, last_name, email, password , role, created_at, updated_at } = req.body;

    const newUser = await User.create({
      user_id,
      first_name,
      last_name,
      password,
      role,
      created_at,
      updated_at,
      email
    });

    res.status(201).json({
      actionStatus: 'Success',
      message: 'Create Success!!',
      statusCode: 200,
      User: newUser
    });
  } catch (err) {
    res.status(400).json({ error: err.message });
  }
};


exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { first_name, last_name, email, password , role, updated_at  } = req.body;
    
    const user = await User.findByPk(id);

    if (user) {
      
      user.first_name = first_name || user.first_name;
      user.last_name = last_name || user.last_name;
      user.password = password || user.password;
      user.role = role || user.role;
      user.updated_at = updated_at || user.updated_at;
      user.email = email || user.email;

      
      await user.save();

      res.status(200).json({
        actionStatus: 'Success',
        message: 'Update Success!!',
        statusCode: 200,
        user: user
      });
    } else {
      res.status(404).json({ error: 'Member not found' });
    }
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};


exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;

    
    const user = await User.findByPk(id);

    if (user) {
      
      await user.destroy();
      res.status(200).json({
        actionStatus: 'Success',
        message: 'Delete Success!!',
        statusCode: 200
      }); 
    } else {
      res.status(404).json({ error: 'Member not found' });
    }
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};
