/**
 * O-04 (rescued from Fase 7) — sidebar "+ New collective" entry (Fase 10.6).
 *
 * Eva starts onboarded with one collective; she opens the sidebar switcher,
 * clicks "+ New collective", fills the modal, and ends up on /lists with
 * both collectives visible in the switcher.
 */
import { test, expect } from '@playwright/test';
import { USERS } from '../fixtures/users.js';
import { loginAs } from '../fixtures/login.js';
import { resetEva } from '../fixtures/db.js';
import { closePool, sql } from '@colectivo/test-utils';

test.describe.configure({ mode: 'serial' });

test.describe('Sidebar create collective (CU-H02 follow-up)', () => {
	test.beforeEach(async () => {
		await resetEva();
	});

	test.afterAll(async () => {
		await resetEva();
		await closePool();
	});

	test('O-04: Eva with one collective creates a second from the sidebar', async ({ page }) => {
		// Onboard Eva with a first collective so the switcher renders.
		const firstName = `Eva First ${Date.now()}`;
		await loginAs(page, USERS.eva, { waitForCollective: false });
		await expect(page).toHaveURL(/\/onboarding$/, { timeout: 15_000 });
		await page.getByTestId('collective-name-input').fill(firstName);
		await page.getByTestId('collective-submit').click();
		await expect(page).toHaveURL(/\/lists$/, { timeout: 15_000 });

		// Open the sidebar switcher and pick "+ New collective".
		await page.getByTestId('sidebar-collective-switcher').click();
		const newEntry = page.getByTestId('sidebar-create-collective');
		await expect(newEntry).toBeVisible({ timeout: 5_000 });
		await newEntry.click();

		const secondName = `Eva Second ${Date.now()}`;
		await page.getByTestId('create-collective-modal-name').fill(secondName);
		await page.getByTestId('create-collective-modal-submit').click();

		// Landed on /lists with the second collective active.
		await expect(page).toHaveURL(/\/lists$/, { timeout: 15_000 });

		// Both collectives in the switcher. Use .first() because the switcher
		// header also renders the active collective name.
		await page.getByTestId('sidebar-collective-switcher').click();
		await expect(
			page.getByTestId('desktop-sidebar').getByText(firstName).first()
		).toBeVisible({ timeout: 5_000 });
		await expect(
			page.getByTestId('desktop-sidebar').getByText(secondName).first()
		).toBeVisible();

		// DB-side: Eva has two collectives.
		const r = await sql(
			'SELECT count(*)::int AS n FROM public.collectives WHERE created_by = $1',
			[USERS.eva.id]
		);
		expect(r.rows[0].n).toBe(2);
	});
});
