package stub

import (
	"fmt"
	"strings"
	"text/template"
)

// GenerateDockerfile generates a minimal Dockerfile for a stub server.
// The Go version is derived from the root go.mod to stay aligned with the project.
func GenerateDockerfile(cfg *Config, goVersion string) (string, error) {
	// Extract major.minor for the Docker image tag (e.g. "1.26.1" → "1.26").
	dockerGoVer := goVersion
	if parts := strings.SplitN(goVersion, ".", 3); len(parts) >= 2 {
		dockerGoVer = parts[0] + "." + parts[1]
	}

	data := dockerfileData{
		Service:   cfg.Service,
		Kind:      cfg.Kind,
		GoVersion: dockerGoVer,
	}

	var b strings.Builder
	if err := dockerfileTmpl.Execute(&b, data); err != nil {
		return "", fmt.Errorf("execute dockerfile template: %w", err)
	}
	return b.String(), nil
}

type dockerfileData struct {
	Service   string
	Kind      Kind
	GoVersion string
}

var dockerfileTmpl = template.Must(template.New("dockerfile").Parse(`# Stub server for {{.Service}} ({{.Kind}})
FROM public.ecr.aws/docker/library/golang:{{.GoVersion}}-alpine AS builder

WORKDIR /build
ARG TARGETARCH
COPY go.mod ./
RUN go mod download
COPY . .
RUN go mod tidy && CGO_ENABLED=0 GOOS=linux GOARCH=${TARGETARCH:-amd64} go build -o /stub-server .

FROM public.ecr.aws/docker/library/alpine:3.19
RUN apk add --no-cache ca-certificates
COPY --from=builder /stub-server /usr/local/bin/stub-server
ENTRYPOINT ["/usr/local/bin/stub-server"]
`))
