import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect, userEvent, fn, within } from 'storybook/test'

import { DeleteConfirmDialog } from './delete-confirm-dialog'
import { InUseError } from '../api/queries'

const meta = {
  component: DeleteConfirmDialog,
  tags: ['ai-generated'],
} satisfies Meta<typeof DeleteConfirmDialog>

export default meta
type Story = StoryObj<typeof meta>

export const Confirms: Story = {
  args: { description: 'Delete this term? This cannot be undone.', onConfirm: fn() },
  play: async ({ canvas, args }) => {
    await userEvent.click(canvas.getByRole('button', { name: 'Delete' }))
    const confirm = await within(document.body).findByRole('button', { name: 'Delete' })
    await userEvent.click(confirm)
    await expect(args.onConfirm).toHaveBeenCalled()
  },
}

export const ShowsInUse: Story = {
  args: {
    description: 'Delete this term? This cannot be undone.',
    onConfirm: async () => { throw new InUseError(7) },
  },
  play: async ({ canvas }) => {
    await userEvent.click(canvas.getByRole('button', { name: 'Delete' }))
    const confirm = await within(document.body).findByRole('button', { name: 'Delete' })
    await userEvent.click(confirm)
    await expect(await within(document.body).findByRole('alert')).toHaveTextContent(/used by 7/i)
  },
}
