package config

import "testing"

func TestOIDCParseDisabledWhenIssuerEmpty(t *testing.T) {
	t.Parallel()
	c, err := loadOIDC(map[string]string{}, OIDCConfig{})
	if err != nil {
		t.Fatalf("load: %v", err)
	}
	if c != nil {
		t.Errorf("expected nil OIDC config when issuer empty; got %+v", c)
	}
}

func TestOIDCRejectMissingClientID(t *testing.T) {
	t.Parallel()
	yaml := OIDCConfig{Issuer: "https://x", ClientSecret: "s"}
	if _, err := loadOIDC(map[string]string{}, yaml); err == nil {
		t.Error("expected error for missing client_id")
	}
}

func TestOIDCRejectMissingClientSecret(t *testing.T) {
	t.Parallel()
	yaml := OIDCConfig{Issuer: "https://x", ClientID: "rm"}
	if _, err := loadOIDC(map[string]string{}, yaml); err == nil {
		t.Error("expected error for missing client_secret")
	}
}

func TestOIDCDefaultsApplied(t *testing.T) {
	t.Parallel()
	yaml := OIDCConfig{
		Issuer: "https://x", ClientID: "rm", ClientSecret: "s",
		RoleMapping: map[string]string{"a": "admin"},
	}
	c, err := loadOIDC(map[string]string{}, yaml)
	if err != nil {
		t.Fatalf("load: %v", err)
	}
	if c.RoleClaim != "groups" {
		t.Errorf("role_claim default: got %q want groups", c.RoleClaim)
	}
	if c.DisplayName != "SSO" {
		t.Errorf("display_name default: got %q want SSO", c.DisplayName)
	}
	wantScopes := []string{"openid", "profile", "email", "groups"}
	if len(c.Scopes) != len(wantScopes) {
		t.Errorf("scopes default: got %v want %v", c.Scopes, wantScopes)
	}
}

func TestOIDCEnvOverrides(t *testing.T) {
	t.Parallel()
	yaml := OIDCConfig{
		Issuer: "https://from-yaml", ClientID: "yaml-id", ClientSecret: "yaml-secret",
		RoleMapping: map[string]string{"x": "admin"},
	}
	envs := map[string]string{
		"RM_OIDC_ISSUER":        "https://from-env",
		"RM_OIDC_CLIENT_ID":     "env-id",
		"RM_OIDC_CLIENT_SECRET": "env-secret",
	}
	c, err := loadOIDC(envs, yaml)
	if err != nil {
		t.Fatalf("load: %v", err)
	}
	if c.Issuer != "https://from-env" || c.ClientID != "env-id" || c.ClientSecret != "env-secret" {
		t.Errorf("env override: got %+v", c)
	}
}
