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

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

async function loadUrls(env: Record<string, string | undefined> = {}) {
  vi.resetModules()
  for (const key of ['NEXT_PUBLIC_STOREFRONT_URL', 'NEXT_PUBLIC_ADMIN_URL']) {
    if (env[key] === undefined) {
      delete process.env[key]
    } else {
      process.env[key] = env[key]
    }
  }
  return import('./urls')
}

afterEach(() => {
  Reflect.deleteProperty(globalThis, 'window')
  delete process.env.NEXT_PUBLIC_STOREFRONT_URL
  delete process.env.NEXT_PUBLIC_ADMIN_URL
  vi.resetModules()
})

describe('dashboard cross-app URLs', () => {
  it('uses default storefront and admin bases on the server', async () => {
    const { storefrontUrl, adminUrl } = await loadUrls()

    expect(storefrontUrl).toBe('http://localhost:3000')
    expect(adminUrl).toBe('http://localhost:3000/admin')
  })

  it('strips trailing slashes from configured absolute URLs', async () => {
    const { storefrontUrl, adminUrl } = await loadUrls({
      NEXT_PUBLIC_STOREFRONT_URL: 'https://market.example.com/',
      NEXT_PUBLIC_ADMIN_URL: 'https://ops.example.com/admin/',
    })

    expect(storefrontUrl).toBe('https://market.example.com')
    expect(adminUrl).toBe('https://ops.example.com/admin')
  })

  it('rewrites local browser fallbacks onto the current production host', async () => {
    installWindow('tenant.rentaldrivego.com', 'https:')
    const { storefrontUrl, adminUrl } = await loadUrls()

    expect(storefrontUrl).toBe('https://tenant.rentaldrivego.com')
    expect(adminUrl).toBe('https://tenant.rentaldrivego.com/admin')
  })

  it('preserves non-URL values after normalizing their trailing slash', async () => {
    const { storefrontUrl, adminUrl } = await loadUrls({
      NEXT_PUBLIC_STOREFRONT_URL: '/storefront/',
      NEXT_PUBLIC_ADMIN_URL: '/admin/',
    })

    expect(storefrontUrl).toBe('/storefront')
    expect(adminUrl).toBe('/admin')
  })
})
