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

test.describe('session history smoke tests', () => {
  test('can filter sessions by ticket and client, then open details', async ({ page }) => {
    const api = await createAuthenticatedApiContext()
    const ticketNumber = `PW-HISTORY-${Date.now()}`
    const clientName = uniqueName('History Client')
    const tree = await createTroubleshootingTree(api, {
      name: uniqueName('Playwright History Flow'),
    })
    const session = await createSession(api, tree.id, {
      ticket_number: ticketNumber,
      client_name: clientName,
    })

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

      await expect(
        page.getByRole('heading', { name: 'Sessions', exact: true }),
      ).toBeVisible()

      await page.getByPlaceholder('Search by ticket number...').fill(ticketNumber)
      await page.getByPlaceholder('Search by client name...').fill(clientName)

      const sessionCard = page.locator('.bg-card').filter({ hasText: ticketNumber }).filter({ hasText: clientName }).first()
      await expect(sessionCard).toBeVisible()
      await expect(sessionCard.getByText(tree.name)).toBeVisible()

      await sessionCard.getByRole('button', { name: 'View Details' }).click()

      await expect(page).toHaveURL(new RegExp(`/sessions/${session.id}$`))
      await expect(page.getByRole('heading', { name: ticketNumber })).toBeVisible()
    } finally {
      await disposeApiContext(api)
    }
  })
})
