package orgpolicy

import (
	"testing"

	"github.com/ultisuite/ulti-backend/internal/auth"
)

func TestAuthAccessPolicyAllowsOpenProviders(t *testing.T) {
	policy := AuthAccessPolicy{
		Providers: []IdentityProviderPolicy{
			{Enabled: true, Slug: "google"},
		},
	}
	claims := &auth.Claims{Email: "user@example.com"}
	if !policy.AllowsIdentity(claims.Email, claims) {
		t.Fatal("expected open provider to allow any identity")
	}
}

func TestAuthAccessPolicyRejectsUnknownDomain(t *testing.T) {
	policy := AuthAccessPolicy{
		Providers: []IdentityProviderPolicy{
			{
				Enabled:             true,
				Slug:                "google",
				AllowedEmailDomains: []string{"company.com"},
			},
		},
	}
	claims := &auth.Claims{Email: "user@gmail.com"}
	if policy.AllowsIdentity(claims.Email, claims) {
		t.Fatal("expected domain restriction to reject identity")
	}
}

func TestAuthAccessPolicyAllowsMatchingOrganization(t *testing.T) {
	policy := AuthAccessPolicy{
		Providers: []IdentityProviderPolicy{
			{
				Enabled:              true,
				Slug:                 "google",
				AllowedOrganizations: []string{"company.com"},
			},
		},
	}
	claims := &auth.Claims{Email: "user@company.com", HD: "company.com"}
	if !policy.AllowsIdentity(claims.Email, claims) {
		t.Fatal("expected matching hosted domain to allow identity")
	}
}

func TestAuthAccessPolicyMatchesSourceSpecificProvider(t *testing.T) {
	policy := AuthAccessPolicy{
		Providers: []IdentityProviderPolicy{
			{
				Enabled:             true,
				Slug:                "corp-google",
				AllowedEmailDomains: []string{"company.com"},
			},
			{
				Enabled:             true,
				Slug:                "partner-google",
				AllowedEmailDomains: []string{"partner.org"},
			},
		},
	}
	claims := &auth.Claims{Email: "user@partner.org", Source: "partner-google"}
	if !policy.AllowsIdentity(claims.Email, claims) {
		t.Fatal("expected source-specific provider rules to allow identity")
	}
}
