# Auto-generated Dockerfile for {{.AppName}}
# Generated by BYOP Engine - Golang Stack Analyzer

# Multi-stage build for Go application
FROM golang:{{.GoVersion}}-alpine AS builder

# Set destination for COPY
WORKDIR /app

{{if .NeedsBuildTools}}
# Install build tools if needed
RUN apk add --no-cache {{.BuildTools | join " "}}
{{end}}

{{if .HasGoMod}}
# Copy go.mod for better dependency caching
COPY go.mod ./
{{if .HasGoSum}}
# Copy go.sum for dependency verification
COPY go.sum ./
{{end}}

# Download dependencies
RUN go mod download
{{else}}
# No go.mod found - using GOPATH mode or vendor
{{if .HasVendor}}
# Copy vendor directory
COPY vendor/ ./vendor/
{{end}}
{{end}}

# Copy the source code (excluding unnecessary files)
COPY . .

{{if .HasGoMod}}
# Ensure dependencies are up to date
RUN go mod tidy
{{end}}

# Build the application
{{if .CGOEnabled}}
RUN CGO_ENABLED=1 {{.BuildCommand}}
{{else}}
RUN CGO_ENABLED=0 {{.BuildCommand}}
{{end}}

# Runtime stage
{{if .NeedsRuntimeDeps}}
FROM alpine:latest

# Install runtime dependencies
RUN apk --no-cache add {{.RuntimeDeps | join " "}}
{{else}}
# Use scratch for minimal footprint (static binary)
FROM scratch
{{end}}

{{if ne .RuntimeImage "scratch"}}
# Create app directory
WORKDIR /app

# Create non-root user for security
RUN adduser -D -s /bin/sh appuser

# Copy the binary from builder
COPY --from=builder /app/{{.BinaryName}} ./{{.BinaryName}}

# Change ownership to non-root user
RUN chown appuser:appuser /app/{{.BinaryName}} && chmod +x /app/{{.BinaryName}}

# Switch to non-root user
USER appuser
{{else}}
# Copy the binary from builder (scratch image)
COPY --from=builder /app/{{.BinaryName}} /{{.BinaryName}}
{{end}}

# Expose port
EXPOSE {{.Port}}

{{if .HealthCheckEndpoint}}
# Add health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD wget --no-verbose --tries=1 --spider http://localhost:{{.Port}}{{.HealthCheckEndpoint}} || exit 1
{{end}}

# Set the command to run the application
{{if ne .RuntimeImage "scratch"}}
CMD ["./{{.BinaryName}}"]
{{else}}
CMD ["/{{.BinaryName}}"]
{{end}}
