import { expect, test } from '@playwright/test'
import {
  createAuthenticatedApiContext,
  createTroubleshootingTree,
  createProceduralTree,
  disposeApiContext,
  uniqueName,
} from './helpers/api'

test.describe('tree editor smoke tests', () => {
  test('can open and edit a troubleshooting flow in the editor', async ({ page }) => {
    const api = await createAuthenticatedApiContext()
    const tree = await createTroubleshootingTree(api, {
      name: uniqueName('PW Edit Troubleshooting'),
      question: 'Is the device powered on?',
    })

    try {
      await page.goto(`/trees/${tree.id}/edit`)

      // Editor should load — look for tree name in the page
      await expect(page.getByText(tree.name)).toBeVisible({ timeout: 10000 })

      // Should see the root question node
      await expect(page.getByText('Is the device powered on?')).toBeVisible()
    } finally {
      await disposeApiContext(api)
    }
  })

  test('can open and edit a procedural flow in the editor', async ({ page }) => {
    const api = await createAuthenticatedApiContext()
    const tree = await createProceduralTree(api, {
      name: uniqueName('PW Edit Procedural'),
    })

    try {
      await page.goto(`/flows/${tree.id}/edit`)

      // Editor should load with step titles visible
      await expect(page.getByText('Verify the server is reachable')).toBeVisible({ timeout: 10000 })
      await expect(page.getByText('Check the service status')).toBeVisible()
      await expect(page.getByText('Restart the service if needed')).toBeVisible()

      // Should be able to add a new step (use first() since there are 2 Add Step buttons)
      const addStepButton = page.getByRole('button', { name: /Add Step/i }).first()
      await addStepButton.click()
    } finally {
      await disposeApiContext(api)
    }
  })
})
