import StatusCodes from 'http-status-codes'
import { Request, Response, Router } from 'express'
import { ApiError, notFoundError, paramMissingError } from '@shared/responseTypes'
import { IBikeTrip } from '@entities/BikeTrip'
import { bikeTripsCollectionName, dbClient, dbName } from '@server'

const router = Router()
const { NOT_FOUND, OK } = StatusCodes

interface QueryParams {
    from: string
    to: string
}

interface IBikeTripsInRangeResponse {
    bikeTrips: IBikeTrip[]
}

interface IBikeTripResponse {
    bikeTrip: IBikeTrip
}

/******************************************************************************
 *         Get Bike Trips in range - "GET /api/bike-trips/all-in-range"
 ******************************************************************************/

router.get('/all-in-range', async (req: Request, res: Response<IBikeTripsInRangeResponse | ApiError>) => {
    const from = Number(req.query.from)
    const to = Number(req.query.to)

    if (!from || !to) {
        return res.status(StatusCodes.BAD_REQUEST).json({error: paramMissingError})
    }

    const bikeTripsCursor = dbClient.db(dbName).collection(bikeTripsCollectionName).aggregate<IBikeTrip>([
        {$match: {startDate: {$gte: from, $lt: to}}}
    ])

    return res.status(OK).json({bikeTrips: await bikeTripsCursor.toArray()})
})



/******************************************************************************
 *         Get single Bike Trip by rentalId - "GET /api/bike-trips/:rentalId"
 ******************************************************************************/

router.get('/:rentalId', async (req: Request, res: Response<IBikeTripResponse | ApiError>) => {
    const { rentalId } = req.params

    if (!rentalId) {
        return res.status(StatusCodes.BAD_REQUEST).json({error: paramMissingError})
    }

    const bikeTrip = await dbClient.db(dbName).collection(bikeTripsCollectionName).findOne({_id: rentalId})

    if (!bikeTrip) {
        return res.status(NOT_FOUND).json({error: notFoundError})
    }

    return res.status(OK).json({bikeTrip: bikeTrip})
})



/******************************************************************************
 *                                 Export
 ******************************************************************************/

export default router
