import express from 'express';
/* IMPORT MIDDLEWARE */
import bp from 'body-parser';
import { Pool, Client } from 'pg';
/* IMPORT CONFIG */
import DBCONFIG from './database-info.json';
import jwt from 'jsonwebtoken';
import * as s3bucketController from './controllers/s3bucketController.js';
/* IMPORT ROUTES */
import home from './routes/home.js';
import item from './routes/item.js';
import login from './routes/login.js';
import search from './routes/search.js';
import stats from './routes/stats.js';
import users from './routes/users.js';

// initalize the express app
const app = express();

const pool = new Pool({
  user: DBCONFIG.dbUser,
  host: DBCONFIG.dbHost,
  database: DBCONFIG.dbDatabase,
  password: DBCONFIG.dbPassword,
  port: DBCONFIG.dbPort,
});

app.locals.pool = pool;

// example query
// pool.query('SELECT * FROM users', (err, res) => {
//   console.log(err, res)
//   pool.end()
// })

app.use(bp.urlencoded({extended: false}));
// lets us read jsons
app.use(bp.json());

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:3000"); //allow this domain to access communicate with the server
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

// test route, root of api, sends example message as response
app.get('/', (req, res) => {
  res.send("you hit the server!");
});

// in development 
app.use('/login', login);
//test auth
app.use('/auth', (req, res, next) => {
    console.log(req.headers.authorization + " PRINTING THIS OUT")
    if(!req.headers.authorization) {
        return res.status(401).json({
            authCheck: false
        });
    }
    const token = req.headers.authorization.split('.')[1];
    //console.log(token);
    return jwt.verify(req.headers.authorization, 'secret', (err, decoded) => {
        if(err) {return res.status(401).json({
            authCheck: false
        });}
        pool.query('SELECT uemail FROM users WHERE uemail=$1', [decoded.email], (err, result) => {
            if(result.rows == null) {
                res.status(401).json({
                    authCheck:false
                })
            }
            return next();
        })
    })
});
app.get('/auth/testauth', (req, res) => {
    res.status(201).json({
        authCheck: true
    })
})

// api definitions
app.use('/api/home', home);
app.use('/api/item', item);
app.use('/api/search', search);
app.use('/api/stats', stats);
app.use('/api/users', users);


// will need to add app.static later on to serve build of reactjs folder


// app starts listening on port 4000
// we would want this as environment variable
app.listen(4000, () => {
  console.log("listening on port 4000");
})
