package staticwebapp

import (
	"alpha.dagger.io/azure"
	"alpha.dagger.io/os"
	"alpha.dagger.io/dagger"
)

// Create a static web app
#StaticWebApp: {
	// Azure Config
	config: azure.#Config

	// ResourceGroup name in which to create static webapp
	rgName: string & dagger.#Input

	// StaticWebApp location
	stappLocation: string & dagger.#Input

	// StaticWebApp name
	stappName: string & dagger.#Input

	// GitHubRepository URL 
	remote: string & dagger.#Input

	// GitHub Branch
	ref: *"main" | string & dagger.#Input

	// Location of your application code
	appLocation: *"/" | string & dagger.#Input

	// Location of your build artifacts
	buildLocation: *"build" | string & dagger.#Input

	// GitHub Personal Access Token
	authToken: dagger.#Secret & dagger.#Input

	// DefaultHostName generated by Azure
	defaultHostName: string & dagger.#Output

	// Container image
	ctr: os.#Container & {
		image: azure.#CLI & {
			"config": config
		}
		always: true

		command: #"""
				az staticwebapp create -n "$AZURE_STATICWEBAPP_NAME" \
										-g "$AZURE_DEFAULTS_GROUP" \
										-l "$AZURE_DEFAULTS_LOCATION" \
										-s "$GIT_URL" \
										-b "$GIT_BRANCH" \
										-t "$(cat /run/secrets/git_pat)" \
										--app-location "$APP_LOCATION" \
										--output-location "$BUILD_LOCATION" | jq -r '.defaultHostname' | tr -d "\n" > /defaultHostName
			"""#

		secret: "/run/secrets/git_pat": authToken

		env: {
			AZURE_DEFAULTS_GROUP:    rgName
			AZURE_DEFAULTS_LOCATION: stappLocation
			AZURE_STATICWEBAPP_NAME: stappName
			GIT_URL:                 remote
			GIT_BRANCH:              ref
			APP_LOCATION:            appLocation
			BUILD_LOCATION:          buildLocation
		}
	}

	// DefaultHostName generated by Azure
	defaultHostName: ({
		os.#File & {
			from: ctr
			path: "/defaultHostName"
		}
	}).contents
}