import { Application } from 'express';
import { Resource } from 'express-automatic-routes';
import { Req, Res } from '#interfaces/IApi';
import verify from '#middlewares/auth';
import { queryModifier } from '#middlewares/query-modifier';
import { SessionService } from '#services/auth';
import { validateQueryZod } from '#middlewares/validators';
import { QueryParamsSchema } from '#contracts/shared';
import { sendSuccess } from '#utils/responseUtils';

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

					const page = Math.max(1, requestPayload.page || 1);
					const pageSize = Math.min(50, Math.max(1, requestPayload.pageSize || 10));
					const sortField = requestPayload.sortField || 'last_activity_at';
					const sortOrder = requestPayload.sortOrder || 'DESC';

					const token = req.cookies?.access_token || req.header('Authorization')?.split(' ')[1] || '';

					// Extract platform filter — delegate parsing to service
					const rawFilter: string = requestPayload.rawFilter || '';
					const platformMatch = rawFilter.match(/(?:^|,)platform:([^,]+)/);
					const platformFilter = platformMatch ? platformMatch[1] : undefined;

					const result = await SessionService.listSessions(
						userId,
						token,
						page,
						pageSize,
						sortField,
						sortOrder,
						platformFilter,
					);

					return sendSuccess(
						res,
						result,
						'Lấy danh sách phiên đăng nhập thành công',
						'Sessions retrieved successfully',
					);
				} catch (error) {
					return res.error(error);
				}
			},
		},
	};
};
