/**
 * (mutation payload contract with locale-scoped redirect_uri; auth-loading gate).
 */
import React from 'react'
import { render, screen } from '@testing-library/react'
import GetTokenWrapper from '../index'

const mockUseAuth = jest.fn()
const mockMutate = jest.fn()

jest.mock('@/providers/auth-provider', () => ({
  useAuth: () => mockUseAuth(),
}))
jest.mock('@/services/auth/auth.mutations', () => ({
  useGetTokenMutation: () => ({ mutate: mockMutate }),
}))

let mockLocale = 'vi'
jest.mock('next-intl', () => ({
  useLocale: () => mockLocale,
}))
jest.mock('@/share/components/full-page/loading', () => ({
  __esModule: true,
  default: () => <div data-testid="get-token-loading">Loading</div>,
}))

describe('[components/auth/get-token] GetTokenWrapper', () => {
  beforeEach(() => {
    mockLocale = 'vi'
    mockUseAuth.mockReturnValue({ isLoading: false })
    mockMutate.mockClear()
  })

  describe('auth session ready', () => {
    it.each([
      ['vi', 'http://localhost/vi/get-token'],
      ['en', 'http://localhost/en/get-token'],
    ] as const)(
      'fires token exchange with redirect_uri for locale %s',
      (locale, expectedRedirectUri) => {
        mockLocale = locale
        render(<GetTokenWrapper code="auth-code-123" />)

        expect(screen.getByTestId('get-token-loading')).toBeInTheDocument()
        expect(mockMutate).toHaveBeenCalledWith({
          code: 'auth-code-123',
          redirect_uri: expectedRedirectUri,
        })
        expect(mockMutate).toHaveBeenCalledTimes(1)
      },
    )
  })

  describe('auth session loading', () => {
    it('shows loading and does not call mutate until auth is ready', () => {
      mockUseAuth.mockReturnValue({ isLoading: true })

      render(<GetTokenWrapper code="auth-code-123" />)

      expect(screen.getByTestId('get-token-loading')).toBeInTheDocument()
      expect(mockMutate).not.toHaveBeenCalled()
    })
  })
})
