# Use the official Golang image to create a build artifact
# This is a multi-stage build pattern
FROM golang:1.21-alpine AS builder

# Install git, ca-certificates and other dependencies needed for Go modules
RUN apk update && apk add --no-cache git ca-certificates tzdata

# Create and change to the app directory
WORKDIR /app

# Copy all source files first to get a proper module graph
COPY . ./

# Build the binary directly without mod tidy (to avoid transitive dependency issues)
RUN go mod init mohportal 2>/dev/null || true && go get -d ./... && CGO_ENABLED=0 GOOS=linux go build -v -o server

# Build the binary
RUN CGO_ENABLED=0 GOOS=linux go build -v -o server

# Use a Docker multi-stage build to create a lean production image
FROM golang:1.21-alpine

# Install ca-certificates for SSL connections
RUN apk --no-cache add ca-certificates

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

# Copy the pre-built binary file from the previous stage
COPY --from=builder /app/server /server

# Copy necessary files
COPY --from=builder /app/static /static
COPY --from=builder /app/templates /templates
COPY --from=builder /app/.env /app/.env

# Change ownership of the binary to the non-root user
RUN chown appuser:appuser /server

# Change to the non-root user
USER appuser

# Expose the port
EXPOSE 17000

# Run the server
CMD ["/server"]