import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { SessionService } from '#services/auth';
import { sendSuccess } from '#utils/responseUtils';
import { GenericError } from '#interfaces/error/generic';

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [verify],
			handler: async (req: Req, res: Res) => {
				try {
					const userId = req.user!.id;
					const sessionId = req.params.id as string;

					if (!sessionId) {
						const error = new GenericError('VALIDATION_ERROR', { field: 'session_id' });
						return res.error(error);
					}

					// Prevent revoking the current session via this endpoint
					const currentToken = req.cookies?.access_token || req.header('Authorization')?.split(' ')[1] || '';
					const currentSessionId = await SessionService.getCurrentSessionId(currentToken);

					if (currentSessionId && currentSessionId === sessionId) {
						const error = new GenericError('VALIDATION_ERROR', {
							field: 'session_id',
							message: 'Cannot revoke current session',
						});
						return res.error(error);
					}

					await SessionService.revokeSession(sessionId, userId, req.ip, req.get('User-Agent'));

					return sendSuccess(res, null);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
