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

export const saveFile = async (file) => {
  if (!file) return null;

  const newFile = new FileModel({
    filename: file.originalname,
    contentType: file.mimetype,
    size: file.size,
    data: file.buffer,
  });

  const savedFile = await newFile.save();
  return savedFile._id;
};

/* REGISTER USER */
export const register = async (req, res) => {
  try {
    const { firstName, lastName, email, password, friends, location, occupation } = req.body;

    const fileId = await saveFile(req.file);

    const salt = await bcrypt.genSalt();
    const passwordHash = await bcrypt.hash(password, salt);

    const newUser = new User({
      firstName,
      lastName,
      email,
      password: passwordHash,
      picture: fileId,
      friends,
      location,
      occupation,
      viewedProfile: Math.floor(Math.random() * 10000),
      impressions: Math.floor(Math.random() * 10000),
    });
    const savedUser = await newUser.save();
    res.status(201).json(savedUser);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

/* LOGGING IN */
export const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ email: email });
    if (!user) return res.status(400).json({ msg: "Invalid credentials. " });

    const isMatch = await bcrypt.compare(password, user.password);
    if (!isMatch) return res.status(400).json({ msg: "Invalid credentials. " });

    // todo https://www.npmjs.com/package/jsonwebtoken
    // https://github.com/auth0/node-jsonwebtoken
    // infos in readme notiert

    // this is the access token
    const accesstoken = jwt.sign({ id: user._id }, process.env.JWT_SECRET, {
      expiresIn: "15m",
      algorithm: "HS256", // symetric
      issuer: "mern-social",
    });

    const refreshToken = jwt.sign({ id: user._id }, process.env.JWT_REFRESH_SECRET, {
      expiresIn: "7d",
      algorithm: "HS256",
      issuer: "mern-social",
    });

    res.cookie("refreshToken", refreshToken, {
      httpOnly: true,
      // secure: process.env.NODE_ENV === "production",
      secure: false, // on localhost!
      sameSite: "lax", // for localhost, else strict possible
      maxAge: 7 * 24 * 60 * 60 * 1000,
    });

    console.log("authenticated, created tokens");

    delete user.password;

    // or ??
    // const userObj = user.toObject();
    // delete userObj.password;
    // res.status(200).json({ token: accesstoken, user: userObj });

    res.status(200).json({ token: accesstoken, user });
  } catch (err) {
    res.status(500).json({ error: err.message + " login failed" });
  }
};
