# Stage 1: Build frontend assets
FROM node:24-alpine AS frontend-builder
WORKDIR /app

# Enable pnpm via corepack
RUN corepack enable pnpm

# Install dependencies
COPY package.json pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile

# Copy source and build assets
COPY . .
RUN pnpm run build:css && pnpm run build:js

# Stage 2: Build Go binary
FROM golang:1.26-alpine AS go-builder
WORKDIR /app

# Download Go modules
COPY go.mod go.sum ./
RUN go mod download

# Copy source code
COPY . .

# Copy built frontend assets from the previous stage
COPY --from=frontend-builder /app/web/static/css/output.css ./web/static/css/
COPY --from=frontend-builder /app/web/static/js/htmx.min.js ./web/static/js/

# Generate templ files using the tool defined in go.mod
RUN go tool templ generate

# Build the optimized binary
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/server ./cmd/schreifuchs-ch

# Stage 3: Final minimal image
FROM alpine:latest
WORKDIR /app

# Copy the compiled binary from the builder stage
COPY --from=go-builder /app/server .

# Expose the application port
EXPOSE 8080

# Set the entrypoint
ENTRYPOINT ["/app/server"]
