# Build stage for web UI
FROM node:20-alpine AS web-builder

# Set working directory for web UI
WORKDIR /web

# Copy web UI files
COPY web/package*.json ./
RUN npm ci

COPY web/ ./
RUN npm run build

# Go build stage
FROM golang:1.24-alpine AS go-builder

# Set working directory
WORKDIR /app

# Install build dependencies
RUN apk add --no-cache git make

# Copy go.mod and go.sum
COPY go.mod .
COPY go.sum* .

# Download dependencies
RUN go mod download

# Copy source code
COPY . .

# Copy web UI files to the correct location
RUN mkdir -p cmd/server/web/out
COPY --from=web-builder /web/out/* cmd/server/web/out/

# Build the application with version information
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o gitea-webhook-ambassador ./cmd/server

# Runtime stage
FROM alpine:3.19

# Add non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Install runtime dependencies
RUN apk add --no-cache ca-certificates tzdata

# Create necessary directories with appropriate permissions
RUN mkdir -p /app/config && \
    chown -R appuser:appgroup /app

WORKDIR /app

# Copy the binary from builder stage
COPY --from=go-builder /app/gitea-webhook-ambassador .

# Copy default config (will be overridden by volume mount in production)
COPY config.yaml /app/config/

# Switch to non-root user
USER appuser

# Expose the service port
EXPOSE 8080

# Default command (can be overridden at runtime)
ENTRYPOINT ["/app/gitea-webhook-ambassador"]
CMD ["-config=/app/config/config.yaml"]