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

import { buildNewTabRouteUrl } from '@/utils/navigation'

describe('buildNewTabRouteUrl', () => {
  const originalLocation = window.location

  beforeEach(() => {
    vi.restoreAllMocks()
  })

  afterEach(() => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: originalLocation,
    })
  })

  it('builds /webapps/{projectKey}/{webAppId} URL in DSS iframe context', () => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: new URL(
        'http://localhost:11200/dip/api/webapps/view/?projectKey=LOCALPROJECT&webAppId=WsYT2lY',
      ),
    })
    vi.spyOn(window, 'self', 'get').mockReturnValue({} as Window & typeof globalThis)
    vi.spyOn(window, 'top', 'get').mockReturnValue({} as Window & typeof globalThis)

    const url = buildNewTabRouteUrl('/ignored', '/traces/abc')

    expect(url).toBe('http://localhost:11200/webapps/LOCALPROJECT/WsYT2lY/traces/abc')
  })

  it('preserves route query in DSS iframe mode', () => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: new URL(
        'http://localhost:11200/dip/api/webapps/view/?projectKey=LOCALPROJECT&webAppId=WsYT2lY',
      ),
    })
    vi.spyOn(window, 'self', 'get').mockReturnValue({} as Window & typeof globalThis)
    vi.spyOn(window, 'top', 'get').mockReturnValue({} as Window & typeof globalThis)

    const url = buildNewTabRouteUrl('/ignored', '/traces/abc?source=pasted')

    expect(url).toBe('http://localhost:11200/webapps/LOCALPROJECT/WsYT2lY/traces/abc?source=pasted')
  })

  it('falls back to absolute resolved URL when DSS iframe params are missing', () => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: new URL('http://localhost:11200/dip/api/webapps/view/?projectKey=LOCALPROJECT'),
    })
    vi.spyOn(window, 'self', 'get').mockReturnValue({} as Window & typeof globalThis)
    vi.spyOn(window, 'top', 'get').mockReturnValue({} as Window & typeof globalThis)

    const url = buildNewTabRouteUrl('/webapps/LOCALPROJECT/WsYT2lY/traces/abc', '/traces/abc')

    expect(url).toBe('http://localhost:11200/webapps/LOCALPROJECT/WsYT2lY/traces/abc')
  })

  it('returns absolute URL outside iframe', () => {
    Object.defineProperty(window, 'location', {
      configurable: true,
      value: new URL('https://dss.example.com/webapps/PRJ/trace-explorer/'),
    })
    vi.spyOn(window, 'self', 'get').mockReturnValue(window)
    vi.spyOn(window, 'top', 'get').mockReturnValue(window)

    const url = buildNewTabRouteUrl('/webapps/PRJ/trace-explorer/traces/abc', '/traces/abc')

    expect(url).toBe('https://dss.example.com/webapps/PRJ/trace-explorer/traces/abc')
  })
})
