/**
 * (metadata, negative ids, happy tryout wrapper).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'

jest.mock('next-intl/server', () => ({
  getTranslations: () =>
    Promise.resolve((key: string) => `layout.${key}`),
}))

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/api-product/tryout', () => ({
  __esModule: true,
  default: ({
    api_id,
    app_id,
    case_id,
  }: {
    api_id: string
    app_id: string
    case_id: string
  }) => (
    <div data-testid="tryout-wrapper">
      {`Tryout:${api_id}:${app_id}:${case_id ?? ''}`}
    </div>
  ),
}))

describe('[locale]/(end-user)/.../tryout/page.tsx', () => {
  beforeEach(() => {
    jest.clearAllMocks()
  })

  describe('generateMetadata', () => {
    it('maps tryout header key via layout namespace mock', async () => {
      const { generateMetadata } = await import('../page')
      const m = await generateMetadata()
      expect(m.title).toBe('layout.header.tryout')
    })
  })

  describe('negative — missing id or app_id', () => {
    it.each([
      {
        label: 'empty id',
        params: { id: '' },
        searchParams: { app_id: 'a', case_id: '' },
      },
      {
        label: 'missing app_id',
        params: { id: 'x' },
        searchParams: { app_id: '', case_id: 'c1' },
      },
    ])('throws after notFound for $label', async ({ params, searchParams }) => {
      const { default: TryoutPage } = await import('../page')

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

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

  describe('happy path', () => {
    it('renders ApiProductTryoutWrapper when id and app_id are non-empty', async () => {
      const { default: TryoutPage } = await import('../page')
      const el = await TryoutPage({
        params: Promise.resolve({ id: 'api-x' }),
        searchParams: Promise.resolve({ app_id: 'app-y', case_id: 'c1' }),
      } as never)

      render(el as React.ReactElement)
      expect(screen.getByTestId('tryout-wrapper')).toHaveTextContent(
        'Tryout:api-x:app-y:c1'
      )
      expect(mockNotFound).not.toHaveBeenCalled()
    })
  })
})
