// conttollers/auth
import { hashPassword, comparePassword } from "../helpers/auth.js";
import User from "../models/user.js";
import { nanoid } from "nanoid";

export const register = async (req, res) => {
  try {
    // decode email, password from token
    const { email, password } = jwt.verify(req.body.token, config.JWT_SECRET);
    // hash password
    const hashedPassword = await hashPassword(password);
    // create user and save
    const user = await new User({
      username: nanoid(6),
      email,
      password: hashedPassword,
    }).save();
    // create token
    const jwtToken = jwt.sign({ _id: user._id }, config.JWT_SECRET, {
      expiresIn: "1d",
    });
    // create refresh token
    const refreshToken = jwt.sign({ _id: user._id }, config.JWT_SECRET, {
      expiresIn: "30d",
    });
    // hide fields
    user.password = undefined;
    user.resetCode = undefined;
    // send response
    return res.json({
      user,
      token: jwtToken,
      refreshToken,
    });
  } catch (err) {
    console.log(err);
    res.json({ error: "Invalid or expired token. Try again." });
  }
};