const express = require('express');
const router = express.Router();
const {
	getAllHotels,
	getHotel,
	bookHotelRoom,
	getHotelRoom,
	checkBookHotelRoom,
	myBookings,
	myBooking,
	payBooking,
} = require('../../controllers/members/hotels');

const { memberAuth, validation } = require('../../middlewares');
const { body } = require('express-validator');

const BookingValidation = [
	body('roomId').notEmpty(),
	body('checkIn')
		.notEmpty()
		.withMessage('checkIn is required')
		.isISO8601()
		.withMessage('checkIn must be a valid date')
		.custom((value) => {
			const now = new Date();
			now.setHours(0, 0, 0, 0);
			const checkInDate = new Date(value);
			if (checkInDate.getTime() < now.getTime()) {
				throw new Error('checkIn cannot be in the past');
			}
			return true;
		}),
	body('checkOut')
		.notEmpty()
		.withMessage('checkOut is required')
		.isISO8601()
		.withMessage('checkOut must be a valid date')
		.custom((value, { req }) => {
			const checkInDate = new Date(req.body.checkIn);
			const checkOutDate = new Date(value);
			if (checkOutDate <= checkInDate) {
				throw new Error('checkOut must be after checkIn');
			}
			const now = new Date();
			now.setHours(0, 0, 0, 0);
			if (checkOutDate.getTime() < now.getTime()) {
				throw new Error('checkOut cannot be in the past');
			}
			return true;
		}),
];

router.get('/bookings', memberAuth, myBookings);
router.post('/bookings/check', [...BookingValidation, validation], memberAuth, checkBookHotelRoom);
router.post('/bookings/pay', memberAuth, payBooking);
router.get('/bookings/:id', memberAuth, myBooking);

router.post('/bookings', [...BookingValidation, validation], memberAuth, bookHotelRoom);

router.get('/rooms/:id', getHotelRoom);

router.get('/', getAllHotels);
router.get('/:id', getHotel);

module.exports = router;
