/* ----------------------------------------------------------------------------

 Question Server
 GitLab: <https://gitlab.com/MrFry/mrfrys-node-server>

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program. If not, see <https://www.gnu.org/licenses/>.

 ------------------------------------------------------------------------- */

import logger from '../utils/logger'
import type { Response, NextFunction } from 'express'
import type { Request } from '../types/basicTypes'

interface Options {
    loggableKeywords: Array<string>
    loggableModules: Array<string>
    exceptions: Array<string>
    excludeFromStats: Array<string>
}

export default function (options: Options): any {
    const loggableKeywords = options ? options.loggableKeywords : undefined
    const loggableModules = options ? options.loggableModules : undefined
    const exceptions = options.exceptions || []
    const excludeFromStats = options.excludeFromStats || []

    return function (req: Request, res: Response, next: NextFunction) {
        res.on('finish', function () {
            // TODO: test this
            const isException = exceptions.some((ex) => {
                return req.url.includes(ex)
            })

            if (isException) {
                return
            }

            let hostname = 'NOHOST'
            if (req.hostname) {
                hostname = req.hostname.replace('www.', '').split('.')[0]
            } else {
                logger.Log('Hostname is undefined!', logger.GetColor('redbg'))
                console.log(req.body)
                console.log(req.query)
                console.log(req.headers)
            }

            const hasLoggableKeyword =
                loggableKeywords &&
                loggableKeywords.some((keyword) => {
                    return req.url.includes(keyword)
                })
            const hasLoggableModule =
                loggableModules &&
                loggableModules.some((keyword) => {
                    return hostname.includes(keyword)
                })
            const toLog = hasLoggableModule || hasLoggableKeyword

            logger.LogReq(req, true, res.statusCode)
            if (toLog) {
                logger.LogReq(req)
            }

            const shouldLogStat = !excludeFromStats.some((ex) => {
                return req.url.includes(ex)
            })

            if (res.statusCode !== 404 && shouldLogStat) {
                logger.LogStat(
                    req.url,
                    hostname,
                    req.session && req.session.user
                        ? req.session.user.id
                        : 'NOUSER'
                )
            }
        })
        next()
    }
}
