/**
 * (metadata contract, negative missing code, happy path, BVA around falsy code).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'

const mockNotFound = jest.fn(() => {
  const err = new Error('NEXT_NOT_FOUND')
  ;(err as unknown as { digest?: string }).digest = 'NEXT_NOT_FOUND'
  throw err
})

jest.mock('next/navigation', () => ({
  notFound: () => mockNotFound(),
}))

jest.mock('@/components/auth/get-token', () => ({
  __esModule: true,
  default: ({ code }: { code: string }) => (
    <div data-testid="get-token-wrapper" data-code={code}>
      {`GetTokenWrapper:${code}`}
    </div>
  ),
}))

describe('[locale]/(auth)/get-token/page.tsx', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  describe('metadata', () => {
    it('exports fixed title string and empty description', async () => {
      const { metadata } = await import('../page')

      expect(metadata.title).toBe('Get Token')
      expect(metadata.description).toBe('')
    })
  })

  describe('negative — missing / falsy code', () => {
    it.each([
      { params: {}, label: 'empty searchParams' },
      { params: { code: undefined }, label: 'undefined code' },
      { params: { code: '' }, label: 'empty string code' },
    ])('calls notFound once and aborts for $label', async ({ params }) => {
      const { default: GetTokenPage } = await import('../page')

      await expect(
        GetTokenPage({
          searchParams: Promise.resolve(params),
        } as never)
      ).rejects.toThrow('NEXT_NOT_FOUND')

      expect(mockNotFound).toHaveBeenCalledTimes(1)
    })
  })

  describe('happy path — code present', () => {
    it('renders GetTokenWrapper with exact code', async () => {
      const { default: GetTokenPage } = await import('../page')

      const element = await GetTokenPage({
        searchParams: Promise.resolve({ code: 'abc123' }),
      } as never)

      render(element as React.ReactElement)

      expect(screen.getByTestId('get-token-wrapper')).toHaveTextContent(
        'GetTokenWrapper:abc123'
      )
    })

    it('BVA: whitespace-only code is truthy — passes through unchanged (no trim)', async () => {
      const { default: GetTokenPage } = await import('../page')

      const element = await GetTokenPage({
        searchParams: Promise.resolve({ code: '  x  ' }),
      } as never)

      render(element as React.ReactElement)
      const node = screen.getByTestId('get-token-wrapper')
      expect(node).toHaveAttribute('data-code', '  x  ')
      expect(mockNotFound).not.toHaveBeenCalled()
    })
  })

  describe('module contract', () => {
    it('default export is an async page function', async () => {
      const { default: GetTokenPage } = await import('../page')
      expect(GetTokenPage).toEqual(expect.any(Function))
      expect(GetTokenPage.constructor.name).toBe('AsyncFunction')
    })
  })
})
