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"`
}

// TriggerConfig holds settings for creating a new build trigger
type TriggerConfig struct {
	Name           string `json:"name"`           // Name of the trigger
	ProjectID      string `json:"project_id"`      // Google Cloud project ID
	Location       string `json:"location"`        // Region where the trigger will be created
	RepositoryName string `json:"repository_name"` // Repository name to use for the trigger
	BranchPattern  string `json:"branch_pattern"`  // Branch pattern that will trigger the build
	ConfigPath     string `json:"config_path"`     // Path to the Cloud Build config file (YAML or JSON)
	Description    string `json:"description,omitempty"` // Optional description for the trigger
	RepositoryType string `json:"repository_type,omitempty"`
	RepositoryURI  string `json:"repository_uri,omitempty"`
}

// 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
}

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

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

	// Set defaults if not specified
	if config.Location == "" {
		config.Location = "asia-east1"
	}

	if config.BranchPattern == "" {
		config.BranchPattern = "master"
	}

	if config.ConfigPath == "" {
		config.ConfigPath = "/cloudbuild.yaml"
	}

	if config.Name == "" {
		config.Name = "test-trigger"
	}

	return &config, nil
}

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

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

	return nil
}
