const express = require("express")
const bodyParser = require("body-parser")
const cookieParser = require("cookie-parser")
const session = require("express-session")
const morgan = require("morgan")
const path = require("path")
const rfs = require("rotating-file-stream")

const app = express()
require("dotenv").config()
exports.app = app

const accessLogStream = rfs.createStream("access.log", {
  size: "10M",
  interval: "1d",
  compress: "gzip",
  path: path.join(__dirname, "log"),
})

const errorLogStream = rfs.createStream("error.log", {
  size: "10M",
  interval: "1d",
  compress: "gzip",
  path: path.join(__dirname, "log"),
})

const config = require("../.serverrc")
const { setIo } = require("./io")

app.use(cookieParser())
app.use(
  morgan("combined", {
    stream: accessLogStream,
    skip: function (req, res) {
      return res.statusCode >= 400
    },
  })
)

// log all requests to access.log
app.use(
  morgan("combined", {
    stream: errorLogStream,
    skip: function (req, res) {
        console.log('statusCode', res.statusCode, res.statusCode <= 400)
        return res.statusCode < 400
    },
  })
)

const server = setIo(app)

const sess = {
  secret: "super-secret-key",
  resave: true,
  saveUninitialized: true,
  cookie: {},
}
if (app.get("env") === "production") {
  app.set("trust proxy", 1)
  sess.cookie.secure = true
}
app.use(session(sess))

app.use(
  bodyParser.json({
    limit: "50mb",
  })
)
app.use(
  bodyParser.urlencoded({
    limit: "50mb",
    extended: true,
  })
)
app.use(require("./root"))

/**
 * Добавляйте сюда свои routers.
 */
app.use("/kfu-m-24-1", require("./routers/kfu-m-24-1"))
app.use("/epja-2024-1", require("./routers/epja-2024-1"))
app.use("/v1/todo", require("./routers/todo"))
app.use("/dogsitters-finder", require("./routers/dogsitters-finder"))
app.use("/kazan-explore", require("./routers/kazan-explore"))
app.use("/edateam", require("./routers/edateam-legacy"))
app.use("/dry-wash", require("./routers/dry-wash"))
app.use("/freetracker", require("./routers/freetracker"))
app.use("/dhs-testing", require("./routers/dhs-testing"))
app.use("/gamehub", require("./routers/gamehub")) 
app.use("/esc", require("./routers/esc"))
app.use('/connectme', require('./routers/connectme'))

app.use(require("./error"))

server.listen(config.port, () =>
  console.log(`Listening on http://localhost:${config.port}`)
)
