/**
 * Unit tests for query-modifier middleware
 *
 * Covers:
 * - H-12: pageSize must be capped at 100 to prevent DoS via full-table scan
 */

import { queryModifier } from '#middlewares/query-modifier';
import { createMockRequest, createMockResponse } from '@helpers/request';

function makeReq(query: Record<string, string>) {
	return createMockRequest({ method: 'GET', query } as any);
}

describe('queryModifier › pageSize cap (H-12)', () => {
	let mockRes: any;
	let next: jest.Mock;

	beforeEach(() => {
		next = jest.fn();
		mockRes = createMockResponse();
	});

	it('defaults to 10 when pageSize is absent', () => {
		const req = makeReq({}) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(10);
		expect(next).toHaveBeenCalledTimes(1);
	});

	it('accepts a pageSize within the allowed range', () => {
		const req = makeReq({ pageSize: '25' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(25);
	});

	it('caps pageSize to 100 when a larger value is requested', () => {
		const req = makeReq({ pageSize: '9999999' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(100);
	});

	it('caps pageSize to 100 for Number.MAX_SAFE_INTEGER', () => {
		const req = makeReq({ pageSize: String(Number.MAX_SAFE_INTEGER) }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(100);
	});

	it('caps at exactly 100 when pageSize equals 100', () => {
		const req = makeReq({ pageSize: '100' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(100);
	});

	it('caps at 100 when pageSize equals 101', () => {
		const req = makeReq({ pageSize: '101' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(100);
	});

	it('defaults to 10 when pageSize is 0', () => {
		const req = makeReq({ pageSize: '0' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(10);
	});

	it('defaults to 10 when pageSize is negative', () => {
		const req = makeReq({ pageSize: '-5' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.pageSize).toBe(10);
	});

	it('sets page to 1 when page is 0', () => {
		const req = makeReq({ page: '0', pageSize: '10' }) as any;
		queryModifier(req, mockRes, next);
		expect(req.payload?.page).toBe(1);
	});

	it('always calls next()', () => {
		const req = makeReq({ pageSize: '50' }) as any;
		queryModifier(req, mockRes, next);
		expect(next).toHaveBeenCalledTimes(1);
	});
});
