/**
 * Advanced listing tests.
 *
 * Tests the "t ver sin" and "t ver todos" flows through the webhook
 * handler, covering DM‑only responses, pagination, and unassigned‑task
 * listings with their instructive notes.
 */
import { describe, test, expect } from 'bun:test';
import { WebhookServer } from '../../src/server';
import { TaskService } from '../../src/tasks/service';
import { SimulatedResponseQueue } from '../helpers/queue';
import { createTestRequest, registerServerTestLifecycle } from '../helpers/server-test-harness';

const testDb = registerServerTestLifecycle();

// ── Tests ──────────────────────────────────────────────────────────────

describe('Advanced listings via WebhookServer', () => {
	test('should process "t ver sin" in group as DM-only with pagination line', async () => {
		// 12 unassigned in the active group
		for (let i = 1; i <= 12; i++) {
			TaskService.createTask({
				description: `Sin dueño ${i}`,
				due_date: '2025-12-31',
				group_id: 'group-id@g.us',
				created_by: '9999999999',
			});
		}
		// 2 assigned (should not appear in "sin")
		TaskService.createTask(
			{
				description: 'Asignada 1',
				due_date: '2025-10-10',
				group_id: 'group-id@g.us',
				created_by: '1111111111',
			},
			[{ user_id: '1234567890', assigned_by: '1111111111' }],
		);
		TaskService.createTask(
			{
				description: 'Asignada 2',
				due_date: '2025-10-11',
				group_id: 'group-id@g.us',
				created_by: '1111111111',
			},
			[{ user_id: '1234567890', assigned_by: '1111111111' }],
		);

		const payload = {
			event: 'messages.upsert',
			instance: 'test-instance',
			data: {
				key: {
					remoteJid: 'group-id@g.us',
					participant: '1234567890@s.whatsapp.net',
				},
				message: { conversation: 't ver sin' },
			},
		};
		const response = await WebhookServer.handleRequest(createTestRequest(payload));
		expect(response.status).toBe(200);

		const out = SimulatedResponseQueue.get();
		expect(out.length).toBeGreaterThan(0);
		for (const r of out) {
			expect(r.recipient.endsWith('@g.us')).toBe(false);
		}
		const msg = out.map(x => x.message).join('\n');
		expect(msg).toContain('No respondo en grupos.');
	});

	test('should process "t ver sin" in DM returning instruction', async () => {
		const payload = {
			event: 'messages.upsert',
			instance: 'test-instance',
			data: {
				key: {
					remoteJid: '1234567890@s.whatsapp.net',
					participant: '1234567890@s.whatsapp.net',
				},
				message: { conversation: 't ver sin' },
			},
		};
		const response = await WebhookServer.handleRequest(createTestRequest(payload));
		expect(response.status).toBe(200);

		const out = SimulatedResponseQueue.get();
		expect(out.length).toBeGreaterThan(0);
		const msg = out.map(x => x.message).join('\n');
		expect(msg).toContain('No tienes tareas pendientes.');
	});

	test('should process "t ver todos" in group showing "Tus tareas" + "Sin dueño" with pagination', async () => {
		// User's tasks (2 assigned)
		TaskService.createTask(
			{
				description: 'Mi Tarea 1',
				due_date: '2025-10-10',
				group_id: 'group-id@g.us',
				created_by: '2222222222',
			},
			[{ user_id: '1234567890', assigned_by: '2222222222' }],
		);
		TaskService.createTask(
			{
				description: 'Mi Tarea 2',
				due_date: '2025-10-11',
				group_id: 'group-id@g.us',
				created_by: '2222222222',
			},
			[{ user_id: '1234567890', assigned_by: '2222222222' }],
		);

		// 12 unassigned to trigger pagination
		for (let i = 1; i <= 12; i++) {
			TaskService.createTask({
				description: `Sin dueño ${i}`,
				due_date: '2025-12-31',
				group_id: 'group-id@g.us',
				created_by: '9999999999',
			});
		}

		const payload = {
			event: 'messages.upsert',
			instance: 'test-instance',
			data: {
				key: {
					remoteJid: 'group-id@g.us',
					participant: '1234567890@s.whatsapp.net',
				},
				message: { conversation: 't ver todos' },
			},
		};
		const response = await WebhookServer.handleRequest(createTestRequest(payload));
		expect(response.status).toBe(200);

		const out = SimulatedResponseQueue.get();
		expect(out.length).toBeGreaterThan(0);
		const msg = out.map(x => x.message).join('\n');
		expect(msg).toContain('No respondo en grupos.');
	});

	test('should process "t ver todos" in DM showing "Tus tareas" + instructive note', async () => {
		TaskService.createTask(
			{
				description: 'Mi Tarea A',
				due_date: '2025-11-20',
				group_id: 'group-2@g.us',
				created_by: '1111111111',
			},
			[{ user_id: '1234567890', assigned_by: '1111111111' }],
		);

		const payload = {
			event: 'messages.upsert',
			instance: 'test-instance',
			data: {
				key: {
					remoteJid: '1234567890@s.whatsapp.net',
					participant: '1234567890@s.whatsapp.net',
				},
				message: { conversation: 't ver todos' },
			},
		};
		const response = await WebhookServer.handleRequest(createTestRequest(payload));
		expect(response.status).toBe(200);

		const out = SimulatedResponseQueue.get();
		expect(out.length).toBeGreaterThan(0);
		const msg = out.map(x => x.message).join('\n');
		expect(msg).toContain('Tus tareas');
		expect(msg).toContain('ℹ️ Para ver tareas sin responsable');
	});
});
