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


//register

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});
    }
};
  //login

  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 credetial.."});

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:"4d"});
res.status(200).json({token, user});
    }catch(error){
res.status(500).json({message:error.message});
    }
  } ;
  