/**
 * (metadata, CertificateStatus ticket path, negative notFound, create wrapper happy path).
 */
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/regTicket/create', () => ({
  __esModule: true,
  default: (p: Record<string, string>) => (
    <div data-testid="create-wrapper">{`${p.scenario_id}-${p.api_id}`}</div>
  ),
}))

jest.mock('@/components/regTicket/status', () => ({
  __esModule: true,
  default: () => <div data-testid="cert-status">CertificateStatus</div>,
}))

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

  describe('generateMetadata', () => {
    it('title uses reg_ticket translation key mock', async () => {
      const { generateMetadata } = await import('../page')
      const m = await generateMetadata()
      expect(m.title).toBe('layout.header.reg_ticket')
    })
  })

  describe('certificate status branch', () => {
    it('renders CertificateStatus when ticket_id is truthy', async () => {
      const { default: Page } = await import('../page')
      const el = await Page({
        searchParams: Promise.resolve({
          ticket_id: 't1',
          scenario_id: '',
          version_id: '',
          application_id: '',
          api_id: '',
        }),
      } as never)
      render(el as React.ReactElement)
      expect(screen.getByTestId('cert-status')).toBeInTheDocument()
      expect(mockNotFound).not.toHaveBeenCalled()
    })
  })

  describe('negative — missing mandatory create params', () => {
    it('delegates to notFound when ticket_id empty but quartet incomplete', async () => {
      const { default: Page } = await import('../page')

      await expect(
        Page({
          searchParams: Promise.resolve({
            scenario_id: 's',
            version_id: '',
            application_id: 'a',
            api_id: 'api',
            ticket_id: '',
          }),
        })
      ).rejects.toThrow('NEXT_NOT_FOUND')

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

  describe('happy path — create wrapper', () => {
    it('renders wrapper with scenario + api ids', async () => {
      const { default: Page } = await import('../page')
      const el = await Page({
        searchParams: Promise.resolve({
          scenario_id: 's1',
          version_id: 'v1',
          application_id: 'app1',
          api_id: 'api1',
          ticket_id: '',
        }),
      } as never)
      render(el as React.ReactElement)
      expect(screen.getByTestId('create-wrapper')).toHaveTextContent('s1-api1')
    })
  })
})
