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 { clearAuthCookies } from '#utils/cookieUtils';

export default (_express: Application) => {
	return <Resource>{
		post: {
			middleware: [verify],
			handler: async (req: Req, res: Res) => {
				try {
					// Get token from cookie or header
					const token = req.cookies?.access_token || req.header('Authorization')?.split(' ')[1];

					if (token) {
						await SessionService.logout(token);
					}

					// Clear HttpOnly cookies using the same options as when they were set
					clearAuthCookies(res);
					return sendSuccess(res, null, 'Đăng xuất thành công', 'Logged out successfully');
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
