const userCreds = require("../userData/userData.json");
const { Client } = require("pg");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const fs = require("fs");
const SECRETKEY = "IUGHIU*&*&^&)*FF&R&RE%R%RRP(*Y(*%C&$^%*)";

const connection = new Client({
  host: "localhost",
  user: "postgres",
  port: 5432,
  password: "password",
  database: "registeredUsers",
});

exports.signup = async (req, res) => {
  let { username, email, password } = req.body;

  try {
    const existingUser = userCreds.find((user) => user.email === email);
    if (existingUser) {
      return res
        .status(400)
        .json({ message: "User already exists, Please try again..." });
    }
    const hashpassword = await bcrypt.hash(password, 10);
    const result = {
      id: userCreds.length + 1,
      username: username,
      password: hashpassword,
      email: email,
    };
    userCreds.push(result);
    const query =
      `INSERT INTO signedUsers (username, password, email) VALUES ($1, $2, $3)`;
    const values = [result.username, result.password, result.email];

    await connection
      .connect()
      .then(() => console.log("Connected to the database"));
    await connection.query(query, values);
    console.log("User inserted into database");

    connection.query("Select * from signedUsers", (err, res) => {
      if (!err) {
        console.log(res.rows);
      } else {
        console.log(err.message);
      }
      connection.end;
    });

    fs.writeFile("./userData.json", JSON.stringify(userCreds), (err) => {
      if (err) {
        return res.status(500).send("Cannot add details to the file");
      }
      return res.json({ status: "Data Added to the file" });
    });
    const signUpToken = jwt.sign(
      { email: result.email, id: result.id, usename: result.username },
      SECRETKEY
    );
    console.log(signUpToken);

    res.status(200).json({ user: result, token: signUpToken });
  } catch (error) {
    console.log(error);
    res.status(500).json({ msg: "Something went wrong" });
  } finally {
    connection.end();
  }
};
