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
}
