require('dotenv').config({
    path: `.env.${ process.env.NODE_ENV }`
});

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const admin = require('firebase-admin');
const sendgrid = require('@sendgrid/mail');
const serviceAccount = require("./serviceAccount.json");

const usdaRoutes = require('./routes/usda.routes');
const scoreRoutes = require('./routes/score.routes');
const userRoutes = require('./routes/user.routes');
const usersRoutes = require('./routes/users.routes');
const contactRoutes = require('./routes/contact.routes');
const forgotPasswordRoutes = require('./routes/forgotpassword.routes');

const decodeIdToken = require('./middlewares/decodeToken');
const isAdmin = require('./middlewares/isAdmin');

const PORT = process.env.PORT;
const app = express();

sendgrid.setApiKey(process.env.SENDGRID_API_KEY);

admin.initializeApp({
    credential: admin.credential.cert(serviceAccount)
});

app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use('/usda', decodeIdToken, usdaRoutes);
app.use('/score', decodeIdToken, scoreRoutes);
app.use('/user', decodeIdToken, isAdmin, userRoutes);
app.use('/users', decodeIdToken, isAdmin, usersRoutes);
app.use('/contact', contactRoutes);
app.use('/resetpassword', forgotPasswordRoutes);

app.get('/ping', (req, res, next) => {
    res.send("OK");
});

app.listen(PORT, function() {
    console.log("Server is running on Port: " + PORT);
});

