const path = require("node:path");
const { Pool } = require("pg");
const express = require("express");
const session = require("express-session");
const passport = require("passport");
const LocalStrategy = require("passport-local");
const fs = require("node:fs");
const bcryptjs = require("bcryptjs");

const pool = new Pool({
  connectionString: "postgres://deez:postgres@smig-ca01:31450/deez",
});

const initSQL = path.join(__dirname, "../migrations/init.sql");

fs.readFile(initSQL, "utf8", (err, data) => {
  if (err) {
    console.error(err);
    return;
  }
  pool.query(data);
});

const app = express();
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");

app.use(session({ secret: "cats", resave: false, saveUninitialized: false }));
app.use(passport.session());
app.use(express.urlencoded({ extended: false }));

app.get("/", (req, res) => res.render("index", { user: req.user }));

app.get("/sign-up", (req, res) => res.render("sign-up-form"));
app.post("/sign-up", async (req, res, next) => {
  try {
    const hashedPassword = await bcryptjs.hash(req.body.password, 10);
    await pool.query("INSERT INTO users (username, password) VALUES ($1, $2)", [
      req.body.username,
      hashedPassword,
    ]);
    res.redirect("/");
  } catch (err) {
    next(err);
  }
});

app.listen(3000, () => console.log("app running on port 3000"));

passport.use(
  new LocalStrategy(async (username, password, done) => {
    try {
      const { rows } = await pool.query(
        "SELECT * FROM users WHERE username = $1",
        [username],
      );
      const user = rows[0];
      const match = await bcryptjs.compare(password, user.password);

      if (!user) {
        return done(null, false, { message: "Incorrect username/password." });
      }

      if (!match) {
        return done(null, false, { message: "incorrect username/password" });
      }

      return done(null, user);
    } catch (err) {
      return done(err);
    }
  }),
);

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser(async (id, done) => {
  try {
    const { rows } = await pool.query("SELECT * FROM users WHERE id= $1", [id]);
    const user = rows[0];
    done(null, user);
  } catch (e) {
    done(e);
  }
});

app.post(
  "/log-in",
  passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/",
  }),
);

app.get("/log-out", (req, res, next) => {
  req.logout((err) => {
    if (err) {
      return next(err);
    }
    res.redirect("/");
  });
});
