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

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

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

describe('admin app URL resolution', () => {
  it('keeps server fallback unchanged without a browser window', () => {
    expect(resolveBrowserAppUrl('http://localhost:3002/admin')).toBe('http://localhost:3002/admin')
  })

  it('removes trailing slash for localhost browser fallbacks', () => {
    installWindow('127.0.0.1')
    expect(resolveBrowserAppUrl('http://localhost:3002/admin/')).toBe('http://localhost:3002/admin')
  })

  it('rewrites fallback origin to the current browser host in production', () => {
    installWindow('admin.rentaldrivego.ma')
    expect(resolveBrowserAppUrl('http://localhost:3002/admin')).toBe('https://admin.rentaldrivego.ma/admin')
  })

  it('resolves server app URLs from forwarded host and protocol', () => {
    expect(resolveServerAppUrl('http://localhost:3002/admin', 'admin.example.com', 'https')).toBe('https://admin.example.com:3002/admin')
  })

  it('falls back when host is missing or the fallback is not parseable', () => {
    expect(resolveServerAppUrl('http://localhost:3002/admin', null)).toBe('http://localhost:3002/admin')
    expect(resolveServerAppUrl('/admin', 'admin.example.com')).toBe('/admin')
  })
})
