const express = require("express");
const cors = require('cors');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const path = require('path');

const dotenv = require('dotenv');

if(process.env.NODE_ENV) {
  console.log(`.env.${process.env.NODE_ENV}`);
  dotenv.config({
    path: `.env.${process.env.NODE_ENV}`
  });
} else {
  dotenv.config();
}

const app = express();
const connectDB = require("./db");


// PUBLIC
const uploadDir = path.join(__dirname, 'uploads');
app.use('/api/public', express.static(uploadDir));

// JSON LIMIT EXPRESS
app.use(express.json({ limit: '50mb' }));
app.use(express.urlencoded({
  extended: true,
  limit: '50mb'
}));

// connect database
connectDB();

// MIDDLEWARE
app.use(passport.initialize());
require('./services/passport')(passport);

// CORS
app.use(cookieParser());

app.use(cors({
  origin: 'http://localhost:3000',
  credentials: true, // if using cookies/auth
}));

// ROUTES (NO AUTH)
app.use('/api/user', require('./routes/user'));

// AUTH
checkAuth = passport.authenticate('jwt', { session: false });
app.use(checkAuth);

// ROUTES WITH AUTH
app.use('/api/campaign', require('./routes/campaign'));
app.use('/api/note', require('./routes/note'));
app.use('/api/folder', require('./routes/folder'));
/*
app.use('/campaign', require('./routes/campaign'));
app.use('/maps', require('./routes/map'));
app.use('/datagen', require('./routes/datagen'));
app.use('/admin', require('./routes/admin'));
*/

app.get("/api/test", (req, res) => {
  console.log("Hey");
  res.json({"message": "Hello from backend!"});
});

app.listen(5000, () => {
  console.log("Server running on port 5000");
});