import type { Meta, StoryObj } from '@storybook/react-vite'
import { expect, userEvent, waitFor, within } from 'storybook/test'
import { http, HttpResponse } from 'msw'

import { ObjectsTable } from './objects-table'

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

export default meta
type Story = StoryObj<typeof meta>

export const Default: Story = {
  play: async ({ canvas }) => {
    await expect(await canvas.findByText('Amphora')).toBeVisible()
    await expect(canvas.getByText('LM-0042')).toBeVisible()
  },
}

// Clicking the Name header sorts ascending and the active header reports its
// aria-sort (the preview already provides the router; URL state lives there).
export const Sorted: Story = {
  play: async ({ canvas }) => {
    await canvas.findByText('Amphora')
    const header = canvas.getByRole('columnheader', { name: /Name/i })
    await userEvent.click(within(header).getByRole('button'))
    await waitFor(() => expect(header).toHaveAttribute('aria-sort', 'ascending'))
  },
}

export const Empty: Story = {
  parameters: {
    msw: {
      handlers: [
        http.get('/api/admin/objects', () =>
          HttpResponse.json({ items: [], total: 0, limit: 50, offset: 0 }),
        ),
      ],
    },
  },
  play: async ({ canvas }) => {
    await waitFor(() =>
      expect(within(canvas.getByRole('table')).getByText(/no objects yet/i)).toBeVisible(),
    )
  },
}
