const path = require('path')
const fs = require('fs')
const express = require('express')
const { createProxyMiddleware } = require('http-proxy-middleware')

const envPath = path.join(__dirname, '../../.env')
if (fs.existsSync(envPath)) {
  require('dotenv').config({ path: envPath })
}

const PORT = Number(process.env.WEB_PORT || 23566)
const API_TARGET = process.env.API_TARGET || 'http://127.0.0.1:23568'
const STATIC_ROOT = path.join(__dirname, '../../frontend/dist')

const app = express()
app.use(
  '/api',
  createProxyMiddleware({
    target: API_TARGET,
    changeOrigin: true,
  }),
)
app.use(express.static(STATIC_ROOT, { maxAge: '1h', index: false }))
app.get(/^\/(?!api).*/, (_req, res) => {
  res.sendFile(path.join(STATIC_ROOT, 'index.html'))
})

app.listen(PORT, '0.0.0.0', () => {
  console.log(`Grade archive web gateway listening on http://0.0.0.0:${PORT}`)
  console.log(`API proxy target: ${API_TARGET}`)
})
