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

/**
 * Unit tests for the InviteLanding redirect basePath logic (fix for #1006).
 *
 * Reproduces the bug where `window.location.pathname === "/api/"` leads to the
 * post-join redirect landing on `https://host/api/?sid=xxx` → 404. The fix
 * strips any `/api` or `/api/vN` prefix before treating pathname as basePath.
 */

// Mirrors the private helper in apps/web/src/Components/InviteLanding/index.tsx.
// Keep this test in sync with that implementation.
function getAppBasePath(pathname: string): string {
  const p = pathname || '/'
  const stripped = p.replace(/^\/api(?:\/v\d+)?(?=\/|$)/, '')
  return stripped.replace(/\/+$/, '')
}

function buildRedirect(pathname: string, sid: string): string {
  const basePath = getAppBasePath(pathname)
  return `https://host${basePath}/${sid ? `?sid=${sid}` : ''}`
}

describe('InviteLanding redirect basePath (#1006)', () => {
  it('normal root pathname → redirects to "/"', () => {
    expect(buildRedirect('/', 'abc')).toBe('https://host/?sid=abc')
  })

  it('"/api/" pathname no longer lands on backend 404 route', () => {
    // Bug repro: before the fix this returned "/api/?sid=abc" → 404.
    expect(buildRedirect('/api/', 'abc')).toBe('https://host/?sid=abc')
  })

  it('"/api" (no trailing slash) is also stripped', () => {
    expect(buildRedirect('/api', 'abc')).toBe('https://host/?sid=abc')
  })

  it('"/api/v1/" is stripped (versioned API path)', () => {
    expect(buildRedirect('/api/v1/', 'abc')).toBe('https://host/?sid=abc')
  })

  it('"/api/v2/space/invite/xxx" strips the /api/vN prefix only', () => {
    // Only the /api[/vN] segment is removed — the remainder is kept so we
    // never accidentally chop off a legitimate sibling deployment path.
    // For the #1006 repro, this branch is defensive; the user normally lands
    // on /api/?invite=xxx, which fully collapses to '/' (covered above).
    expect(buildRedirect('/api/v2/space/invite/xxx', 'abc')).toBe(
      'https://host/space/invite/xxx/?sid=abc'
    )
  })

  it('subpath deployment ("/web/") is preserved', () => {
    // Non-/api subpath must still be preserved for legacy deployments.
    expect(buildRedirect('/web/', 'abc')).toBe('https://host/web/?sid=abc')
  })

  it('"/apiary/" is NOT stripped (only matches exact /api segment)', () => {
    // Regex uses boundary `(?=\/|$)` so /apiary is left alone.
    expect(buildRedirect('/apiary/', 'abc')).toBe('https://host/apiary/?sid=abc')
  })

  it('empty sid produces no query string', () => {
    expect(buildRedirect('/', '')).toBe('https://host/')
    expect(buildRedirect('/api/', '')).toBe('https://host/')
  })
})
