import dotenv = require('dotenv');
dotenv.config();

import express = require('express');
import cors = require('cors');
import morgan = require('morgan');
const app = express()
app.use(morgan('dev', {
  skip: (req) => {
    return req.path === '/members/me';
  }
}))

app.use(cors({
  origin: [process.env.CLIENT_URL], // your SPA origins
  credentials: true
}));

app.use(express.json())

app.set('trust proxy', 1);

const port = process.env.SERVER_PORT;

//glitchtip setup
import sentry = require('@sentry/node');
if (process.env.DISABLE_GLITCHTIP === "true") {
  console.log("Glitchtip disabled")
} else {
  let dsn = process.env.GLITCHTIP_DSN;
  let release = process.env.APPLICATION_VERSION;
  let environment = process.env.APPLICATION_ENVIRONMENT;
  console.log(release, environment)
  sentry.init({ dsn: dsn, release: release, environment: environment, integrations: [sentry.captureConsoleIntegration({ levels: ['error'] })] });
  console.log("Glitchtip initialized");
}

//session setup
import path = require('path');
import session = require('express-session');
import passport = require('passport');
const SQLiteStore = require('connect-sqlite3')(session);

app.use(session({
  secret: 'whatever',
  resave: false,
  saveUninitialized: false,
  store: new SQLiteStore({ db: 'sessions.db', dir: './' }),
  cookie: {
    httpOnly: true,
    sameSite: 'lax',
    domain: process.env.CLIENT_DOMAIN
  }
}));
app.use(passport.authenticate('session'));

// Mount route modules
import { applicationRouter } from './routes/applications';
import { memberRanks, ranks } from './routes/ranks';
import { memberRouter } from './routes/members';
import { loaRouter } from './routes/loa';
import { status, memberStatus } from './routes/statuses';
import { authRouter } from './routes/auth';
import { roles, memberRoles } from './routes/roles';
import { courseRouter, eventRouter } from './routes/course';
import { calendarRouter } from './routes/calendar';

app.use('/application', applicationRouter);
app.use('/ranks', ranks);
app.use('/memberRanks', memberRanks);
app.use('/members', memberRouter);
app.use('/loa', loaRouter);
app.use('/status', status)
app.use('/memberStatus', memberStatus)
app.use('/roles', roles)
app.use('/memberRoles', memberRoles)
app.use('/course', courseRouter)
app.use('/courseEvent', eventRouter)
app.use('/calendar', calendarRouter)
app.use('/', authRouter)

app.get('/ping', (req, res) => {
  res.status(200).json({ message: 'pong' });
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port} `)
})
