import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { ChatMessageAttachment } from './ChatMessageAttachment'
import { ChatAttachmentModel } from '../../../store/chat/models'

const testAttachment: ChatAttachmentModel = {
  fileId: 'test-file-id',
  fileName: 'test-file-name.jpg',
  contentType: 'image/jpeg',
  fileSize: 5,
}

test('renders a button and a hidden link', () => {
  render(<ChatMessageAttachment attachment={testAttachment} getAttachmentLocation={jest.fn()} />)

  expect(screen.getByRole('button', { name: 'Download' })).toBeInTheDocument()
  expect(screen.getByRole('link')).toBeInTheDocument()
  expect(screen.getByRole('link')).toHaveAttribute('download', testAttachment.fileName)
})

test('clicking the button generates a new download link, sets the href attribute on the hidden link', async () => {
  const mockGetAttachmentLocation = jest.fn().mockResolvedValue('https://example.com/test-file-name.jpg')
  render(<ChatMessageAttachment attachment={testAttachment} getAttachmentLocation={mockGetAttachmentLocation} />)

  const downloadButton = screen.getByRole('button', { name: 'Download' })
  userEvent.click(downloadButton)

  const hiddenLink = screen.getByRole('link')
  await waitFor(() => expect(downloadButton).not.toBeDisabled())
  expect(hiddenLink).toHaveAttribute('href', 'https://example.com/test-file-name.jpg')
})

test('when getting the attachment location fails, an error is displayed', async () => {
  const mockGetAttachmentLocation = jest.fn().mockRejectedValue('')
  render(<ChatMessageAttachment attachment={testAttachment} getAttachmentLocation={mockGetAttachmentLocation} />)

  const downloadButton = screen.getByRole('button', { name: 'Download' })
  userEvent.click(downloadButton)

  await screen.findByText('Error while downloading the attachment.')
})
