const { getDB } = require('../../../utils/mongo')

let db = null

const connect = async () => {
    db = await getDB('stc-21-03')
}

const _idToId = (data) => {
    const { _id, ...rest } = data

    return {
        id: _id, ...rest,
    }
}

const FILM_TOMATOS_COLL = 'films-tomatos'
const getFilmData = async (filmId) => {
    if (db === null) throw new Error('no db connection')

    const filmsCollection = db.collection(FILM_TOMATOS_COLL)
    const data = await filmsCollection.find({
        filmId,
    }).toArray()

    if (data.length === 0) {
        const newData = {
            filmId,
            views: 0,
            ratings: [],
            likes: 0,
        }

        filmsCollection.insertMany([newData])

        return _idToId(newData)
    }
    const filmData = data[0]
    filmsCollection.updateOne({
        filmId,
    }, [
        {
            $set: {
                views: ++filmData.views,
            },
        },
    ])
    return _idToId(filmData)
}

const setLike = async (filmId) => {
    if (db === null) throw new Error('no db connection')

    const filmsCollection = db.collection(FILM_TOMATOS_COLL)
    const data = await filmsCollection.find({
        filmId,
    }).toArray()

    if (data.length === 0) {
        throw new Error('no film data')
    }

    const filmData = data[0]
    filmsCollection.updateOne({
        filmId,
    }, [
        {
            $set: {
                likes: ++filmData.likes,
            },
        },
    ])
    return _idToId(filmData)
}

const setRating = async ({ filmId, rating }) => {
    if (db === null) throw new Error('no db connection')

    const filmsCollection = db.collection(FILM_TOMATOS_COLL)
    const data = await filmsCollection.find({
        filmId,
    }).toArray()

    if (data.length === 0) {
        throw new Error('no film data')
    }

    const filmData = data[0]
    filmData.ratings = [...filmData.ratings, rating]
    filmsCollection.updateOne({
        filmId,
    }, [
        {
            $set: {
                ratings: filmData.ratings,
            },
        },
    ])
    return _idToId(filmData)
}

module.exports = {
    connect,
    getFilmData,
    setLike,
    setRating,
}
