const express = require("express");
const router = express.Router();
const jwt = require("jsonwebtoken");
const bcrypt = require("bcrypt");

import User from "../models/user.js";

//AUTH
router.post("/register", async (req, res) => {
  const { name, email, password } = req.body;
  const passEncrypted = bcrypt.hashSync(password, 10);

  const newUser = new User({
    name: name,
    email: email,
    password: password,
  });

  const emailUser = await User.findOne({ email: email });
  if (emailUser) {
    return res
      .status(500)
      .json({ status: "fail", error: "email already exists" });
  }

  try {
    newUser.password = await newUser.encryptPassword(password);
    await newUser.save();

    res.json({
      status: "ok",
      msg: "Usuario creado",
    });
  } catch (error) {
    return res
      .status(500)
      .json({ status: "fail", error: `internal error:${error}` });
  }
});

router.post("/login", async (req, res) => {
  const { email, password } = req.body;

  var user = await User.findOne({ email: email });
  if (!user) {
    res.status(401).json({ status: "fail", error: "Invalid credentials email" });
    return;
  }
  
  if (! await user.matchPassword(password)) {
   return res.status(401).json({ status: "fail", error: "Invalid credentials pass" });
    
  }
  user.set("password", undefined, { strict: false });
  const token = jwt.sign(
    {
      userData: user,
    },
    "api finanzas mdchaparror @4050#",
    { expiresIn: 60 * 60 * 24 * 30 }
  );
  const toSend = {
    status: "ok",
    userData: user,
    token: token,
  };
  res.json(toSend);
});

//CRUD USER

module.exports = router;
