const router = require("express").Router();
const fs = require('fs');
const userAg = require('useragent');
const logger = require('../helpers/logger');
const dbClickLogger = require("../helpers/dbClickLogger");
const dbClickDisplay = require("../helpers/dbClickDisplay");

const bcrypt = require('bcrypt');

logger.info('Login Routes Loaded');

const users = [
    { 
      id: 1, 
      username: 'admin', 
      password: '$2a$10$Z5WeLISv3h48Yp4UnPFugerOdPHpI/LahB7pW41MtlPw7zyzTAjM2' // bcrypt hash of the password 'password123'
    }
  ];
  
  router.get("/login", async(req, res) =>{
    let data = {
        title: 'Emergency Locksmith',
        url: req.url,
        location: ""
    }
    res.render("pages/loginView"); 
    });

    router.post("/login", async(req, res) =>{
        const { username, password } = req.body;
      
        const user = users.find(u => u.username === username);
      
        if (user && await bcrypt.compare(password, user.password)) {
          req.session.userId = user.id;
          res.redirect('/site-conv-clicks'); // Redirect to protected route after login
        } else {
          res.send('Invalid credentials');
        }
    });

    router.post('/logout', (req, res) => {
        req.session.destroy(err => {
          if (err) {
            return res.redirect('/site-conv-clicks');
          }
          res.clearCookie('sid'); // The cookie name might vary depending on the express-session settings
          res.redirect('/login');
        });
    });
  
    const requireAuth = (req, res, next) => {
        if (!req.session.userId) {
        return res.redirect('/login');
        }
        next();
    };

    router.get("/site-conv-clicks", requireAuth, async(req, res) =>{
        const clickLogs = await dbClickDisplay(req);
        // console.log(clickLogs);
        let data = {
            title: 'SiteWide Conversion Clicks',
            url: req.url,
            clickLogs: clickLogs,
            location: ""
        }
        res.render("pages/convClicksView", data); 
    });

module.exports = router;