package integration

import (
	"strings"
	"testing"

	"github.com/k-capehart/go-salesforce/v3"
	"github.com/stretchr/testify/assert"
)

// ==============================================================================
// Authentication Tests with go-salesforce
// ==============================================================================

// TestGoSF_Auth_Valid tests valid authentication
func TestGoSF_Auth_Valid(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test")
	}

	sf := newGoSFClient(t)
	if sf == nil {
		t.Skip("go-salesforce client not available")
	}

	// Verify we can make a call (implies valid session)
	var accounts []Account
	err := sf.Query("SELECT Id FROM Account LIMIT 1", &accounts)
	assert.NoError(t, err, "Should be able to query with valid auth")
}

// TestGoSF_Auth_InvalidCredentials tests invalid authentication handling
func TestGoSF_Auth_InvalidCredentials(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test")
	}

	baseURL := GetBaseURL()

	// Use Client Credentials flow with INVALID secrets
	_, err := salesforce.Init(salesforce.Creds{
		Domain:         baseURL,
		ConsumerKey:    "bad-client-id",
		ConsumerSecret: "bad-secret",
	})

	assert.Error(t, err, "Auth should fail with invalid credentials")
	// Verify error message or code if possible (depends on mock/server response)
	// NexusCRM backend mock returns 400 or 401
	if err != nil {
		assert.True(t, strings.Contains(err.Error(), "authentication failed") || strings.Contains(err.Error(), "400") || strings.Contains(err.Error(), "401"), "Error should indicate auth failure: "+err.Error())
	}
}

// TestGoSF_Auth_InvalidDomain tests invalid domain handling
func TestGoSF_Auth_InvalidDomain(t *testing.T) {
	if testing.Short() {
		t.Skip("Skipping integration test")
	}

	// Use a domain that doesn't exist or isn't running NexusCRM
	// But go-salesforce might fail connection before auth.
	// Let's use localhost:0 to fail connection
	_, err := salesforce.Init(salesforce.Creds{
		Domain:         "http://localhost:0",
		ConsumerKey:    "test-gosf-client",
		ConsumerSecret: "test-gosf-secret-123",
	})

	assert.Error(t, err, "Auth should fail with invalid domain")
}
