/**
 * (query key factory; success and error branches for parseToken).
 */
jest.mock('@/i18n/navigation', () => ({
  useRouter: () => ({ replace: jest.fn() }),
  Link: ({ href, children }: any) => <a href={href}>{children}</a>,
}))

jest.mock('@/share/layout/end-user/header/hook', () => ({
  useGetUrlLoginMutation: () => ({ mutate: jest.fn() }),
}))

import React from 'react'
import { renderHook, waitFor } from '@testing-library/react'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

import authApi from '@/services/auth/auth.service'

import { authKeys, useParseToken } from '@/services/auth/auth.query-options'

jest.mock('@/services/auth/auth.service', () => ({
  __esModule: true,
  default: {
    parseToken: jest.fn(),
  },
}))

function createWrapper() {
  const client = new QueryClient({
    defaultOptions: {
      queries: { retry: false },
    },
  })
  return function Wrapper({ children }: { children: React.ReactNode }) {
    return (
      <QueryClientProvider client={client}>{children}</QueryClientProvider>
    )
  }
}

describe('[components/auth/sign-up/status] parseTokenKeys & useParseToken', () => {
  beforeEach(() => {
    ;(authApi.parseToken as jest.Mock).mockReset()
  })

  describe('authKeys.parseToken', () => {
    it('defines all segment and per-token key', () => {
      expect(authKeys.all).toEqual(['auth'])
      expect(authKeys.parseToken('invite-1')).toEqual([
        'auth',
        'invite-1',
        'parseToken',
      ])
    })
  })

  describe('useParseToken', () => {
    it('calls parseToken with token and exposes response on success', async () => {
      const payload = { message: 'ok', code: '200', data: {} }
      ;(authApi.parseToken as jest.Mock).mockResolvedValue(payload)

      const { result } = renderHook(() => useParseToken('tok-xyz'), {
        wrapper: createWrapper(),
      })

      await waitFor(() => expect(result.current.isSuccess).toBe(true))

      expect(authApi.parseToken).toHaveBeenCalledWith('tok-xyz')
      expect(authApi.parseToken).toHaveBeenCalledTimes(1)
      expect(result.current.data).toEqual(payload)
    })

    it('marks query error when parseToken rejects', async () => {
      ;(authApi.parseToken as jest.Mock).mockRejectedValue(new Error('bad token'))

      const { result } = renderHook(() => useParseToken('bad'), {
        wrapper: createWrapper(),
      })

      await waitFor(() => expect(result.current.isError).toBe(true))
      expect(result.current.error).toBeDefined()
    })
  })
})
