/**
 * (metadata, negative trimmed token → notFound, happy path + BVA).
 */
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/call-back', () => ({
  __esModule: true,
  default: ({ token }: { token: string }) => (
    <div data-testid="callback-wrapper" data-token={token}>
      {`CallbackWrapper:${token}`}
    </div>
  ),
}))

describe('[locale]/callback/page.tsx — CallbackPage', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

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

  describe('negative — missing or blank token after trim', () => {
    it.each([
      { label: 'token absent', params: {} as Record<string, string> },
      { label: 'token undefined', params: { token: undefined } as never },
      { label: 'empty string', params: { token: '' } },
      { label: 'whitespace only', params: { token: '   \t  ' } },
    ])('throws after notFound for $label', async ({ params }) => {
      const { default: CallbackPage } = await import('../page')

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

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

  describe('happy path', () => {
    it('renders CallbackWrapper with trimmed token', async () => {
      const { default: CallbackPage } = await import('../page')

      const element = await CallbackPage({
        searchParams: Promise.resolve({ token: '  tok-1  ' }),
      } as never)

      render(element as React.ReactElement)

      const node = screen.getByTestId('callback-wrapper')
      expect(node).toHaveAttribute('data-token', 'tok-1')
      expect(mockNotFound).not.toHaveBeenCalled()
    })

    it('BVA: single non-space character survives trim', async () => {
      const { default: CallbackPage } = await import('../page')

      const element = await CallbackPage({
        searchParams: Promise.resolve({ token: ' a ' }),
      } as never)

      render(element as React.ReactElement)
      expect(screen.getByTestId('callback-wrapper')).toHaveAttribute(
        'data-token',
        'a'
      )
    })
  })

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