package cloudbuild

import (
	"context"
	"fmt"
	"os"

	"golang.org/x/oauth2/google"
)

// AuthConfig represents authentication configuration
type AuthConfig struct {
	AccessToken string // Bearer token
}

// LoadAuthFromEnv loads authentication information from environment variables
func LoadAuthFromEnv() *AuthConfig {
	// Try to load access token from environment variables using standard names
	var accessToken string
	
	// Alternative environment variable names (excluding GOOGLE_ACCESS_TOKEN)
	for _, envVar := range []string{"CLOUDBUILD_TOKEN", "GCP_ACCESS_TOKEN", "GOOGLE_OAUTH_TOKEN"} {
		if token := os.Getenv(envVar); token != "" {
			accessToken = token
			break
		}
	}

	return &AuthConfig{
		AccessToken: accessToken,
	}
}

// GetAccessToken gets the access token either from the provided config,
// from environment variables, or falls back to application default credentials
func GetAccessToken(ctx context.Context, authConfig *AuthConfig) (string, error) {
	// If auth config is provided and has access token, use it
	if authConfig != nil && authConfig.AccessToken != "" {
		return authConfig.AccessToken, nil
	}

	// Try to load from environment
	envAuth := LoadAuthFromEnv()
	if envAuth.AccessToken != "" {
		return envAuth.AccessToken, nil
	}

	// Fall back to application default credentials
	tokenSource, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform")
	if err != nil {
		return "", fmt.Errorf("error getting default token source: %w", err)
	}

	token, err := tokenSource.Token()
	if err != nil {
		return "", fmt.Errorf("error getting token: %w", err)
	}

	return token.AccessToken, nil
}

// CreateEnvFile creates a .env file with authentication information
func CreateEnvFile(path string, accessToken string) error {
	content := fmt.Sprintf("# Google Cloud Build authentication\n"+
		"GOOGLE_ACCESS_TOKEN=%s\n\n"+
		"# Your project configuration\n"+
		"CLOUDBUILD_PROJECT_ID=vison-code\n"+
		"CLOUDBUILD_LOCATION=asia-east1\n", accessToken)

	return os.WriteFile(path, []byte(content), 0600)
}
