import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { requireSensitiveConfirm } from '#middlewares/sensitive-confirm';
import { SessionService } from '#services/auth';
import { clearAuthCookies } from '#utils/cookieUtils';
import { sendSuccess } from '#utils/responseUtils';

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

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

					// Clear cookies for web clients
					clearAuthCookies(res);
					return sendSuccess(res, null, 'Đăng xuất tất cả thiết bị thành công', 'All devices logged out successfully');
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
