import { describe, expect, it } from 'vitest';
import {
  buildGenericOidcProviderConfigs,
  buildSsoDiscovery,
  listSsoStartupWarnings,
} from './sso.js';

describe('SSO provider config helpers', () => {
  it('builds OIDC configs for Authentik, WorkOS, and Keycloak when fully configured', () => {
    const configs = buildGenericOidcProviderConfigs({
      AUTHENTIK_CLIENT_ID: 'authentik-client',
      AUTHENTIK_CLIENT_SECRET: 'authentik-secret',
      AUTHENTIK_ISSUER: 'https://authentik.example.com',
      WORKOS_CLIENT_ID: 'workos-client',
      WORKOS_CLIENT_SECRET: 'workos-secret',
      WORKOS_ISSUER: 'https://auth.workos.com/sso/client_123',
      KEYCLOAK_CLIENT_ID: 'keycloak-client',
      KEYCLOAK_CLIENT_SECRET: 'keycloak-secret',
      KEYCLOAK_ISSUER: 'https://sso.example.com/realms/mosaic',
    });

    expect(configs.map((config) => config.providerId)).toEqual(['authentik', 'workos', 'keycloak']);
    expect(configs.find((config) => config.providerId === 'workos')).toMatchObject({
      discoveryUrl: 'https://auth.workos.com/sso/client_123/.well-known/openid-configuration',
      pkce: true,
      requireIssuerValidation: true,
    });
    expect(configs.find((config) => config.providerId === 'keycloak')).toMatchObject({
      discoveryUrl: 'https://sso.example.com/realms/mosaic/.well-known/openid-configuration',
      pkce: true,
    });
  });

  it('exposes Keycloak SAML fallback when OIDC is not configured', () => {
    const providers = buildSsoDiscovery({
      KEYCLOAK_SAML_LOGIN_URL: 'https://sso.example.com/realms/mosaic/protocol/saml',
    });

    expect(providers.find((provider) => provider.id === 'keycloak')).toMatchObject({
      configured: true,
      loginMode: 'saml',
      samlFallback: {
        configured: true,
        loginUrl: 'https://sso.example.com/realms/mosaic/protocol/saml',
      },
    });
  });

  it('reports partial provider configuration as startup warnings', () => {
    const warnings = listSsoStartupWarnings({
      WORKOS_CLIENT_ID: 'workos-client',
      KEYCLOAK_CLIENT_ID: 'keycloak-client',
    });

    expect(warnings).toContain(
      'workos OIDC is partially configured. Missing: WORKOS_CLIENT_SECRET, WORKOS_ISSUER',
    );
    expect(warnings).toContain(
      'keycloak OIDC is partially configured. Missing: KEYCLOAK_CLIENT_SECRET, KEYCLOAK_ISSUER',
    );
  });
});
