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

 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 cookie from 'cookie'

import logger from '../utils/logger'
import dbtools from '../utils/dbtools'
import { Socket } from '../types/basicTypes'

import { testUser } from './auth.middleware'

interface Options {
    userDB: any
}

export default function SocketAuth(options: Options): any {
    const { userDB } = options

    return (socket: Socket, next: (arg0?: any) => void) => {
        try {
            const cookies = cookie.parse(socket.handshake.headers.cookie || '')
            const sessionID = cookies.sessionID

            if (process.env.NS_NOUSER) {
                socket.user = testUser
                next()
                return
            }

            if (!sessionID) {
                next(new Error('Not authenticated, please log in'))
                return
            }

            const user = GetUserBySessionID(userDB, sessionID)

            if (!user) {
                next(new Error('Not authenticated, please log in'))
                return
            }
            socket.user = user
            next()
        } catch (e) {
            next(new Error('Authentication server error'))
            console.error('Authentication server error')
            console.error(e)
        }
    }
}

function GetUserBySessionID(db: any, sessionID: string) {
    logger.DebugLog(`Getting user from db`, 'auth', 2)

    const session = dbtools.Select(db, 'sessions', {
        id: sessionID,
    })[0]

    if (!session) {
        return
    }

    const user = dbtools.Select(db, 'users', {
        id: session.userID,
    })[0]

    if (user) {
        return user
    }
}
