import User from "../models/User.js";
import bcrypt from 'bcrypt'
import jwt from 'jsonwebtoken'

export const registerUser = async(req,res) => {
    try{
const {username,password} = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
const user = await User.create({username,password:hashedPassword});
res.status(201).json(user);
    }catch(error){
res.status(500).json({message:error.message});
    }
};

export const loginUser = async (req,res) => {
    try{
const {username,password} = req.body;
const user = await User.findOne({username});
if(!user)
    return res.status(400).json({message:"invalid creadtial"});

const ismatch = await bcrypt.compare(password, user.password);
if(!ismatch) return res.status(400).json({message:"invalid password"});

const token = jwt.sign({id:user._id}, process.env.JWT_SECRET || "secret", {expiresIn:"7d"});
res.status(200).json({token, user});
    }catch(error){
res.status(500).json({message:error.message});
    }
};

export const getAllUsers = async (req, res) => {
    try {
        const users = await User.find();
        res.json(users);
    } catch (error) {
        res.status(500).json({ message: "Failed to get users" });
    }
}