import { afterEach, describe, expect, it } from 'vitest'
import { resolveBrowserAppUrl } from './appUrls'

function installWindow(hostname: string, protocol = 'https:') {
  Object.defineProperty(globalThis, 'window', {
    configurable: true,
    value: { location: { hostname, protocol } },
  })
}

afterEach(() => {
  Reflect.deleteProperty(globalThis, 'window')
})

describe('dashboard resolveBrowserAppUrl', () => {
  it('returns the fallback untouched on the server', () => {
    expect(resolveBrowserAppUrl('http://localhost:3001/dashboard')).toBe('http://localhost:3001/dashboard')
  })

  it('keeps local browser fallbacks local and removes trailing slash', () => {
    installWindow('localhost')
    expect(resolveBrowserAppUrl('http://localhost:3001/dashboard/')).toBe('http://localhost:3001/dashboard')
  })

  it('rewrites fallback origin to the current production host', () => {
    installWindow('tenant.example.com', 'https:')
    expect(resolveBrowserAppUrl('http://localhost:3001/dashboard')).toBe('https://tenant.example.com/dashboard')
  })

  it('falls back safely when the configured value is not a URL', () => {
    installWindow('tenant.example.com')
    expect(resolveBrowserAppUrl('/dashboard/')).toBe('/dashboard/')
  })
})
