package cloudbuild

import (
	"fmt"

	"google.golang.org/api/cloudbuild/v2"
)

// LinkRepository links a repository to Cloud Build
// It creates a repository resource in Cloud Build that points to the specified repository
// in the source provider (GitHub, GitLab, etc.)
func (c *Client) LinkRepository(projectID, location, connectionName, repoName, remoteURI string) error {
	// Format the connection name as required by the API (this is the parent for repository creation)
	connectionRef := fmt.Sprintf("projects/%s/locations/%s/connections/%s", projectID, location, connectionName)
	
	// Create a repository object with the required remoteUri field
	repository := &cloudbuild.Repository{
		RemoteUri: remoteURI, // The API requires the remote URI to be specified
	}
	
	// Make the API call to create/link the repository
	_, err := c.service.Projects.Locations.Connections.Repositories.Create(
		connectionRef,  // The parent (connection)
		repository,     // Repository object with required fields
	).RepositoryId(repoName).Do() // Set the repository ID
	
	if err != nil {
		return fmt.Errorf("error linking repository: %w", err)
	}
	
	return nil
}

// GetRepository retrieves information about a specific repository
func (c *Client) GetRepository(projectID, location, connectionName, repoName string) (*cloudbuild.Repository, error) {
	// Format the repository name as required by the API
	repoFullName := fmt.Sprintf("projects/%s/locations/%s/connections/%s/repositories/%s", 
		projectID, location, connectionName, repoName)
	
	// Make the API call to get the repository
	repo, err := c.service.Projects.Locations.Connections.Repositories.Get(repoFullName).Do()
	
	if err != nil {
		return nil, fmt.Errorf("error getting repository: %w", err)
	}
	
	return repo, nil
}
