import { describe, expect, it } from 'vitest'
import { getAuthRuntimeConfig, validateAuthRuntimeConfig } from '../auth/auth-env'

describe('getAuthRuntimeConfig', () => {
  it('normalizes loopback origins to the current browser origin', () => {
    const config = getAuthRuntimeConfig({
      VITE_SUPERTOKENS_API_DOMAIN: 'http://localhost:3001/',
      VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'http://127.0.0.1:4273/',
      VITE_AUTH_API_BASE_URL: 'http://localhost:3001/',
    }, {
      locationOrigin: 'http://127.0.0.1:4273',
    })

    expect(config.superTokensWebsiteDomain).toBe('http://127.0.0.1:4273')
    expect(config.authApiBaseUrl).toBe('http://localhost:3001')
  })

  it('warns when auth runtime still targets local development origins', () => {
    const validation = validateAuthRuntimeConfig({
      VITE_SUPERTOKENS_API_DOMAIN: 'http://localhost:3001',
      VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'http://localhost:4273',
      VITE_AUTH_API_BASE_URL: 'http://localhost:3001',
    })

    expect(validation.ready).toBe(true)
    expect(validation.warnings).toContain('VITE_SUPERTOKENS_API_DOMAIN still targets a loopback/local-development origin.')
    expect(validation.warnings).toContain('VITE_SUPERTOKENS_WEBSITE_DOMAIN still targets a loopback/local-development origin.')
    expect(validation.warnings).toContain('VITE_AUTH_API_BASE_URL still targets a loopback/local-development origin.')
  })

  it('warns when public auth config still uses insecure http or split backends', () => {
    const validation = validateAuthRuntimeConfig({
      VITE_SUPERTOKENS_API_DOMAIN: 'http://api.hypertwist.app',
      VITE_SUPERTOKENS_WEBSITE_DOMAIN: 'http://hypertwist.app',
      VITE_AUTH_API_BASE_URL: 'https://auth.hypertwist.app',
    })

    expect(validation.warnings).toContain('VITE_SUPERTOKENS_API_DOMAIN uses HTTP on a non-loopback origin; use HTTPS before public launch.')
    expect(validation.warnings).toContain('VITE_SUPERTOKENS_WEBSITE_DOMAIN uses HTTP on a non-loopback origin; use HTTPS before public launch.')
    expect(validation.warnings).toContain('VITE_AUTH_API_BASE_URL differs from VITE_SUPERTOKENS_API_DOMAIN; verify both point at the same auth backend.')
  })
})
