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

test.describe('flow library start-session smoke tests', () => {
  test('can start a troubleshooting session directly from a search result', async ({ page }) => {
    const api = await createAuthenticatedApiContext()
    const tree = await createTroubleshootingTree(api, {
      name: uniqueName('Playwright Direct Start Flow'),
      question: 'Did the library launch open the flow?',
    })

    try {
      await page.goto('/trees')

      await expect(
        page.getByRole('heading', { name: 'Flow Library' }),
      ).toBeVisible()

      await page.getByPlaceholder('Search flows...').fill(tree.name)
      await page.getByRole('button', { name: 'Search', exact: true }).click()

      const treeCard = page.locator('.bg-card').filter({ hasText: tree.name }).first()
      await expect(treeCard).toBeVisible()
      await treeCard.getByRole('button', { name: /^Start(?: Session)?$/ }).click()

      await expect(page).toHaveURL(new RegExp(`/trees/${tree.id}/navigate$`))
      await expect(page.getByRole('heading', { name: tree.name })).toBeVisible()
      await expect(page.getByRole('button', { name: 'Start Troubleshooting' })).toBeVisible()

      await page.getByPlaceholder('e.g., INC0012345').fill('PW-DIRECT-START')
      await page.getByPlaceholder('e.g., Acme Corp').fill('Direct Start Client')
      await page.getByRole('button', { name: 'Start Troubleshooting' }).click()

      await expect(
        page.getByRole('heading', { name: 'Did the library launch open the flow?' }),
      ).toBeVisible()
    } finally {
      await disposeApiContext(api)
    }
  })
})
