import { beforeEach, describe, expect, it, vi } from 'vitest'

import { transactionsApi } from './transactions'

describe('transactionsApi.diagnoseMissing', () => {
  beforeEach(() => {
    vi.restoreAllMocks()
  })

  it('distinguishes missing explorer and missing rpc results', async () => {
    const fetchMock = vi.fn()
      .mockResolvedValueOnce({
        ok: false,
        status: 404,
        json: async () => ({ message: 'Not found' }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: null }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: null }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: '0x39fb85' }),
      })

    vi.stubGlobal('fetch', fetchMock)

    const diagnostic = await transactionsApi.diagnoseMissing(
      138,
      '0x14d7259e6e75bbcd8979dc9e19f3001b0f328bbcdb730937f8cc2e6a52f26da6'
    )

    expect(diagnostic.checked_hash).toBe('0x14d7259e6e75bbcd8979dc9e19f3001b0f328bbcdb730937f8cc2e6a52f26da6')
    expect(diagnostic.chain_id).toBe(138)
    expect(diagnostic.explorer_indexed).toBe(false)
    expect(diagnostic.rpc_transaction_found).toBe(false)
    expect(diagnostic.rpc_receipt_found).toBe(false)
    expect(diagnostic.latest_block_number).toBeTypeOf('number')
    expect(diagnostic.rpc_url).toBe('https://rpc-http-pub.d-bis.org')
  })

  it('reports when rpc can still see a transaction the explorer has not indexed', async () => {
    const fetchMock = vi.fn()
      .mockResolvedValueOnce({
        ok: false,
        status: 404,
        json: async () => ({ message: 'Not found' }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: { hash: '0xabc' } }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: null }),
      })
      .mockResolvedValueOnce({
        ok: true,
        json: async () => ({ result: '0x10' }),
      })

    vi.stubGlobal('fetch', fetchMock)

    const diagnostic = await transactionsApi.diagnoseMissing(138, '0xabc')

    expect(diagnostic.explorer_indexed).toBe(false)
    expect(diagnostic.rpc_transaction_found).toBe(true)
    expect(diagnostic.rpc_receipt_found).toBe(false)
    expect(diagnostic.latest_block_number).toBe(16)
  })
})
