const express = require('express');
const { body } = require('express-validator');
const { isAuth, validation } = require('../../../middlewares');
const {
	getMyListings,
	updateListing,
	forceDeleteListing,
	softDeleteListing,
	getListingById,
} = require('../../../controllers/host/listings');
const { jsonParser } = require('../../../helpers');

const router = express.Router();
router.get('/', isAuth, getMyListings);

router.patch(
	'/:listingId',
	isAuth,
	jsonParser,
	[
		body('data.name').notEmpty().optional(),
		body('data.description').optional(),
		body('data.locationType').optional(),
		body('data.addressCountry').trim().notEmpty().optional(),
		body('data.addressStreet').trim().notEmpty().optional(),
		body('data.addressApt').optional({
			values: 'falsy',
		}),
		body('data.addressCity').trim().notEmpty().optional(),
		body('data.addressState').trim().notEmpty().optional(),
		body('data.addressZip').trim().notEmpty().optional(),
		body('data.longitude').optional().isFloat().withMessage('Longitude must be a number'),
		body('data.latitude').optional().isFloat().withMessage('Latitude must be a number'),
		body('data.price')
			.optional()
			.isDecimal({ decimal_digits: '2' })
			.withMessage('Price must be a decimal with at most 2 decimal places'),
		body('data.minCapacity').optional().isInt({ min: 1 }).withMessage('Minimum capacity must be at least 1'),
		body('data.maxCapacity')
			.optional()
			.isInt({ min: 1 })
			.withMessage('Maximum capacity must be at least 1')
			.custom((value, { req }) => {
				if (value && req.body.min_capacity && value < req.body.min_capacity) {
					throw new Error('Maximum capacity must be greater than or equal to minimum capacity');
				}
				return true;
			}),
		body('data.checkInTime').optional(),
		body('data.checkOutTime').optional(),
		body('data.cancellationPolicy')
			.optional()
			.isIn([
				'Cancellation and Refund Policy: 7-day full refund; 24-hour grace period (48-hour advance booking required)',
				'24-Hour Cancellation Window: Full Refund Guaranteed',
			])
			.withMessage('Invalid cancellation policy'),
		body('data.bathroom').optional().isInt({ min: 0 }).withMessage('Bathroom must be a non-negative integer'),
		body('data.kitchen').optional().isInt({ min: 0 }).withMessage('Kitchen must be a non-negative integer'),
		body('data.bedroom').optional().isInt({ min: 0 }).withMessage('Bedroom must be a non-negative integer'),
		body('data.guidelines').optional().isString().withMessage('Guidelines must be a string'),
		body('data.safetyAndSecurity').optional().isString().withMessage('Safety and security must be a string'),
	],
	validation,
	updateListing,
);

router.delete('/soft-delete/:listingId', isAuth, softDeleteListing);

router.delete('/:listingId', isAuth, forceDeleteListing);
router.get('/:listingId', isAuth, getListingById);

module.exports = router;
