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

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

afterEach(() => {
  vi.resetModules()
  for (const key of ['NEXT_PUBLIC_WEBSITE_URL', 'NEXT_PUBLIC_CARPLACE_URL', 'NEXT_PUBLIC_ADMIN_URL']) {
    delete process.env[key]
  }
})

describe('application URLs', () => {
  it('uses the website as the canonical public origin', async () => {
    const { websiteUrl, carplaceUrl, adminUrl } = await loadUrls()
    expect(websiteUrl).toBe('http://localhost:3000')
    expect(carplaceUrl).toBe('http://localhost:3000/carplace')
    expect(adminUrl).toBe('http://localhost:3000/admin')
  })

  it('accepts explicit Carplace and admin URLs', async () => {
    const { websiteUrl, carplaceUrl, adminUrl } = await loadUrls({
      NEXT_PUBLIC_WEBSITE_URL: 'https://rentaldrivego.ma/',
      NEXT_PUBLIC_CARPLACE_URL: 'https://rentaldrivego.ma/carplace/',
      NEXT_PUBLIC_ADMIN_URL: 'https://rentaldrivego.ma/admin/',
    })
    expect(websiteUrl).toBe('https://rentaldrivego.ma')
    expect(carplaceUrl).toBe('https://rentaldrivego.ma/carplace')
    expect(adminUrl).toBe('https://rentaldrivego.ma/admin')
  })

  it('adds the Carplace path when only an origin is supplied', async () => {
    const { carplaceUrl } = await loadUrls({ NEXT_PUBLIC_CARPLACE_URL: 'https://market.example.com' })
    expect(carplaceUrl).toBe('https://market.example.com/carplace')
  })
})
