/**
 * Dashboard proofshots — seeds the admin account with test data so every
 * widget is visible, then captures 6 screenshots (3 viewports × 2 themes).
 *
 * Seeded data is removed in afterAll so it doesn't pollute other tests.
 */
import { test } from '@playwright/test';
import { execSync } from 'child_process';
import { captureProofshots } from './proofshots';

// A real document that exists in the dev DB (most recently updated)
const SEED_DOC_ID = '24580ce9-9765-40b1-ac59-b0ab15160ce0';
const SEED_DOC_TITLE = 'Brief aus dem Krieg';

// Real comment IDs used as reference_id for deep-linking
const COMMENT_IDS = [
	'46c5171f-1721-4085-a7ed-1eef7b4effb8',
	'a09cefe4-ddf8-47fa-addc-5c582183b459'
];

const psql = (sql: string) =>
	execSync(
		`docker exec archive-db psql -U archive_user family_archive_db -c "${sql.replace(/"/g, '\\"')}"`
	);

test.beforeAll(() => {
	// Insert a MENTION and a REPLY notification for the admin user so the
	// notifications widget is populated in the screenshots.
	psql(`
    INSERT INTO notifications (recipient_id, type, document_id, reference_id, read, actor_name)
    SELECT id, 'MENTION', '${SEED_DOC_ID}', '${COMMENT_IDS[0]}', false, 'Berit Hoffmann'
    FROM users WHERE username = 'admin';

    INSERT INTO notifications (recipient_id, type, document_id, reference_id, read, actor_name)
    SELECT id, 'REPLY',   '${SEED_DOC_ID}', '${COMMENT_IDS[1]}', false, 'Marcel Raddatz'
    FROM users WHERE username = 'admin';
  `);
});

test.afterAll(() => {
	// Remove only the seeded rows (identified by the sentinel actor names)
	psql(`
    DELETE FROM notifications
    WHERE actor_name IN ('Berit Hoffmann', 'Marcel Raddatz')
      AND recipient_id = (SELECT id FROM users WHERE username = 'admin');
  `);
});

captureProofshots('/', 'dashboard', {
	setup: async (page) => {
		// Navigate to '/' first so the browser has an origin for localStorage,
		// then inject the lastVisited entry directly — no document page load needed.
		await page.goto('/');
		await page.waitForLoadState('domcontentloaded');
		await page.evaluate(
			({ id, title }) => {
				localStorage.setItem('familienarchiv.lastVisited', JSON.stringify({ id, title }));
			},
			{ id: SEED_DOC_ID, title: SEED_DOC_TITLE }
		);
	}
});
