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

test.describe('shared session management smoke tests', () => {
  test('created shares appear in exports and can be revoked', async ({ page }) => {
    const api = await createAuthenticatedApiContext()
    const tree = await createTroubleshootingTree(api, {
      name: uniqueName('Playwright Exports Flow'),
    })
    const session = await createSession(api, tree.id, {
      ticket_number: `PW-EXPORTS-${Date.now()}`,
      client_name: 'Exports Client',
    })
    const share = await createSessionShare(api, session.id, {
      visibility: 'public',
      share_name: uniqueName('Playwright Exports Share'),
    })

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

      await expect(
        page.getByRole('heading', { name: 'My Shared Sessions' }),
      ).toBeVisible()
      await expect(page.getByText(share.share_name || '')).toBeVisible()

      const shareCard = page.locator('.bg-card').filter({ hasText: share.share_name || '' }).first()
      await shareCard.getByRole('button', { name: 'Revoke' }).click()

      const confirmDialog = page.getByRole('dialog', { name: 'Revoke Share Link' })
      await expect(confirmDialog).toBeVisible()
      await confirmDialog.getByRole('button', { name: 'Revoke' }).click()

      await expect(page.getByText(share.share_name || '')).not.toBeVisible()
    } finally {
      await disposeApiContext(api)
    }
  })
})
