import { test, expect } from '@playwright/test';

test.beforeEach(async ({ page }) => {
    // Reset database before each test
    await page.request.post('/api/test/reset');
});

test.describe('Note Linking', () => {
    test('should create new note from broken link', async ({ page }) => {
        // Create initial note
        await page.goto('/notes/new');
        await page.fill('input[name="title"]', 'Parent Note');
        await page.fill('textarea[name="content"]', 'Content with [[Unlinked Child Note]]');
        await page.click('button[type="submit"]');
        
        // Click the unlinked note
        await page.click('a.note-link');
        
        // Verify new note form with title pre-filled
        await expect(page).toHaveURL('/notes/new');
        await expect(page.locator('input[name="title"]')).toHaveValue('Unlinked Child Note');
        
        // Create child note
        await page.fill('textarea[name="content"]', 'Child content');
        await page.click('button[type="submit"]');
        
        // Verify child note creation
        await expect(page.locator('h1')).toHaveText('Unlinked Child Note');
        await expect(page.locator('.content')).toContainText('Child content');
    });

    test('should navigate between linked notes', async ({ page }) => {
        // Create two linked notes
        await page.goto('/notes/new');
        await page.fill('input[name="title"]', 'First Note');
        await page.fill('textarea[name="content"]', 'Links to [[Second Note]]');
        await page.click('button[type="submit"]');
        const firstNoteUrl = page.url();
        
        await page.click('a.note-link');
        await page.fill('textarea[name="content"]', 'Links back to [[First Note]]');
        await page.click('button[type="submit"]');
        const secondNoteUrl = page.url();
        
        // Verify bidirectional linking
        await page.goto(firstNoteUrl);
        await page.click('a.note-link:has-text("Second Note")');
        await expect(page).toHaveURL(secondNoteUrl);
        
        await page.click('a.note-link:has-text("First Note")');
        await expect(page).toHaveURL(firstNoteUrl);
    });
});