require('dotenv').config()
const express = require('express')
const app = express()

const fs = require('fs');
// const privateKey = fs.readFileSync('./ssl/key.txt', 'utf8');
// const certificate = fs.readFileSync('./ssl/crt.txt', 'utf8');
// const credentials = {key: privateKey, cert: certificate};

const server = require("http").createServer(app);
// const server = require("https").createServer(credentials, app);

const cors = require('cors')
const path = require('path');
const port = process.env.PORT || 3006

const {sequelize} = require('./models')
const apiRoutes = require('./routes/api')
const dbRoutes = require('./routes/db')
const webhookRoutes = require('./routes/webhooks')

const main = async () => {
    app.use(cors())

    await sequelize.authenticate();
    console.log('Connected to the database');
    // await sequelize.sync(); // This will create tables based on your defined models
    // console.log('Tables synchronized');

    // static files
    app.use('/uploads', express.static('uploads'))
    app.use('/', express.static(path.join(__dirname, 'web/build')));
    app.use('/admin', express.static(path.join(__dirname, 'admin/dist')));

    app.use('/webhooks', webhookRoutes)

    app.use(express.json());

    app.use('/api', apiRoutes)

    app.use('/db', dbRoutes)

    app.get('/admin*', (req, res, next) => {
        if (/(.ico|.js|.css|.jpg|.png|.map)$/i.test(req.path)) {
            next();
        } else {
            res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
            res.header('Expires', '-1');
            res.header('Pragma', 'no-cache');
            res.sendFile(path.join(__dirname, 'admin', 'dist', 'index.html'));
        }
    });

    app.get('*', (req, res, next) => {
        if (/(.ico|.js|.css|.jpg|.png|.map)$/i.test(req.path)) {
            next();
        } else {
            res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
            res.header('Expires', '-1');
            res.header('Pragma', 'no-cache');
            res.sendFile(path.join(__dirname, 'web', 'build', 'index.html'));
        }
    });


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

try {
    main()
} catch (e) {
    console.log("Server crashed!", e)
}
