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

const { resolveModelQuirkOverrides, spawnMock } = vi.hoisted(() => ({
  resolveModelQuirkOverrides: vi.fn(),
  spawnMock: vi.fn(),
}))

vi.mock('#cli/core/model-quirks', () => ({
  resolveModelQuirkOverrides,
}))

vi.mock('node:child_process', () => ({
  spawn: spawnMock,
}))

const {
  applyOAuthModelQuirks,
  openOAuthBrowserUrl,
  resolveActiveOpenAiBaseUrl,
} = await import('../src/dimsdk/pages/utils/oauth-dialog-runtime.ts')

const realOpen = globalThis.open
const realProcess = globalThis.process

afterEach(() => {
  resolveModelQuirkOverrides.mockReset()
  spawnMock.mockReset()
  Object.defineProperty(globalThis, 'open', {
    configurable: true,
    value: realOpen,
  })
  Object.defineProperty(globalThis, 'process', {
    configurable: true,
    value: realProcess,
  })
  delete process.env.DIMCODE_TEMPERATURE
  delete process.env.DIMCODE_INTERLEAVED_THINKING
})

describe('oauth dialog runtime helpers', () => {
  it('prefers the active store base url over env fallbacks', () => {
    const resolved = resolveActiveOpenAiBaseUrl(
      {
        state: {
          config: {
            baseUrl: 'https://store.example/v1/',
          },
        },
      } as Parameters<typeof resolveActiveOpenAiBaseUrl>[0],
      {
        DIMCODE_OPENAI_BASE_URL: 'https://env.example/v1',
        OPENAI_BASE_URL: 'https://legacy.example/v1',
      },
    )

    expect(resolved).toBe('https://store.example/v1')
  })

  it('uses window.open in browser mode when available', async () => {
    const open = vi.fn()
    Object.defineProperty(globalThis, 'open', {
      configurable: true,
      value: open,
    })

    await expect(
      openOAuthBrowserUrl('https://example.com/login', false),
    ).resolves.toBe(true)

    expect(open).toHaveBeenCalledWith(
      'https://example.com/login',
      '_blank',
      'noopener,noreferrer',
    )
  })

  it('applies model quirks to the store and node env without any fallback shims', async () => {
    resolveModelQuirkOverrides.mockReturnValue({
      temperature: 0.2,
      interleavedThinking: true,
    })

    const store = {
      state: {
        config: {
          temperature: 1,
          interleaved_thinking: false,
        },
      },
      setEnvVar: vi.fn(),
    } as Parameters<typeof applyOAuthModelQuirks>[0]['store']

    applyOAuthModelQuirks({
      modelId: 'gpt-test',
      store,
    })

    expect(store?.state.config.temperature).toBe(0.2)
    expect(store?.state.config.interleaved_thinking).toBe(true)
    expect(store?.setEnvVar).toHaveBeenCalledWith('DIMCODE_TEMPERATURE', '0.2')
    expect(store?.setEnvVar).toHaveBeenCalledWith(
      'DIMCODE_INTERLEAVED_THINKING',
      '1',
    )

    applyOAuthModelQuirks({
      modelId: 'gpt-test',
      nodeLike: true,
    })

    expect(process.env.DIMCODE_TEMPERATURE).toBe('0.2')
    expect(process.env.DIMCODE_INTERLEAVED_THINKING).toBe('1')
  })
})
