const express = require('express');
const { body } = require('express-validator');
const {
	driverAccountCreate,
	driverLogin,
	getProfile,
	updateDriver,
	logout,
} = require('../../controllers/drivers/accounts');
const { driverAuth, validation } = require('../../middlewares');
const { allMembers } = require('../../controllers/members/accounts');

const router = express.Router();

const driverValidation = [
	body('emailAddress').notEmpty().withMessage('Email is required').isEmail().withMessage('Invalid email format'),
	body('phoneNo').notEmpty().withMessage('Phone number is required'),
	body('password').notEmpty().withMessage('Password is required'),
	body('confirmPassword')
		.notEmpty()
		.withMessage('Confirm password is required')
		.custom((value, { req }) => {
			if (value !== req.body.password) {
				throw new Error('Passwords do not match!');
			}
			return true;
		}),

	body('licenseNo').notEmpty().withMessage('License number is required'),
	body().custom((value, { req }) => {
		const { driverPhoto, vehiclePhoto } = req.files;

		if (!driverPhoto?.[0] || !vehiclePhoto?.[0]) {
			throw new Error('Driver and vehicle photos are required');
		}
		return true;
	}),
];

router.post('/register', driverValidation, driverAccountCreate);
router.post('/login', driverLogin);
router.get('/profile', driverAuth, getProfile);
router.patch(
	'/profile',
	driverAuth,
	[
		body('driverName').optional().notEmpty().withMessage('Driver name cannot be empty'),
		body('conductorName').optional().notEmpty().withMessage('Conductor name cannot be empty'),
		body('shuttleNumber').optional().notEmpty().withMessage('Shuttle number cannot be empty'),
		body('plateNumber').optional().notEmpty().withMessage('Plate number cannot be empty'),
		body('status').optional().isIn(['online', 'offline']).withMessage('Status must be online or offline'),
		body('longitude').optional().isDecimal().withMessage('Longitude must be a decimal value'),
		body('latitude').optional().isDecimal().withMessage('Latitude must be a decimal value'),
		validation,
	],
	updateDriver,
);

router.post('/logout', driverAuth, logout);

router.get('/members', driverAuth, allMembers);

module.exports = router;
