package config

import (
	"encoding/json"
	"fmt"
	"os"
)

// Config represents the configuration for the Cloud Build client
type Config struct {
	ProjectID       string             `json:"project_id"`
	Location        string             `json:"location"`
	DefaultConnType string             `json:"default_conn_type"`
	Connections     []ConnectionConfig `json:"connections,omitempty"`
}

// ConnectionConfig represents a connection configuration
type ConnectionConfig struct {
	Name        string                 `json:"name"`
	Disabled    bool                   `json:"disabled"`
	Annotations map[string]string      `json:"annotations,omitempty"`
	GitlabConfig *GitlabConnectionConfig `json:"gitlab_config,omitempty"`
}

// GitlabConnectionConfig represents GitLab-specific connection configuration
type GitlabConnectionConfig struct {
	HostURI             string `json:"host_uri"`
	WebhookSecretVersion string `json:"webhook_secret_version"`
	ReadTokenVersion    string `json:"read_token_version"`
	AuthTokenVersion    string `json:"auth_token_version"`
}

// LoadConfig loads the configuration from a JSON file
func LoadConfig(path string) (*Config, error) {
	data, err := os.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("failed to read config file: %w", err)
	}

	var config Config
	if err := json.Unmarshal(data, &config); err != nil {
		return nil, fmt.Errorf("failed to parse config file: %w", err)
	}

	// Set defaults if not specified
	if config.Location == "" {
		config.Location = "global"
	}

	if config.DefaultConnType == "" {
		config.DefaultConnType = "GITHUB"
	}

	return &config, nil
}

// SaveConfig saves the configuration to a JSON file
func SaveConfig(config *Config, path string) error {
	data, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return fmt.Errorf("failed to marshal config: %w", err)
	}

	if err := os.WriteFile(path, data, 0644); err != nil {
		return fmt.Errorf("failed to write config file: %w", err)
	}

	return nil
}
