const express = require('express');
const app = express();
const session = require('express-session');
const port = 3000;
const flash = require('express-flash');
const expressLayouts = require('express-ejs-layouts');
const passport = require('passport');
const fs = require('fs');
const https = require('https');
const privateKey = fs.readFileSync('./SSL_certification/ssl.key', 'utf8');
const certificate = fs.readFileSync('./SSL_certification/STAR_ntunhs_edu_tw.crt', 'utf8');
const credentials = { key: privateKey, cert: certificate };
require('dotenv').config();

app.use(expressLayouts);
app.set('layout', './layouts/layout');
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.use(express.static(__dirname + '/public'));
app.use(flash());
app.use(express.json());

const pagesInfo = require('./controller/pages/pagesInfo');
app.use(pagesInfo);

const initalizePassport = require('./models/passport/passport-config');
initalizePassport(passport);

const seesionStore = require('./models/passport/session-config');
app.use(
    session({
        secret: process.env.SESSION_SECRET,
        resave: false,
        saveUninitialized: true,
        store: seesionStore,
        cookie: {
            maxAge: 24 * 60 * 60 * 1000,
        },
    })
);

//passport
app.use(passport.initialize());
app.use(passport.session());

//路徑
const router = require('./routes/router');
app.use('/', router);
const apiRouter = require('./routes/api');
app.use('/api', apiRouter);

var httpsServer = https.createServer(credentials, app);
httpsServer.listen(3443, function(){
    console.log('Https server is running at https://localhost:3443')
});

app.listen(port, () => {
    console.log(`Server is running at port ${port}`);
});

require('./config/deleteZIP'); //壓縮檔自動刪除(5小時刪除一天前的檔案)
