# ===== Builder Stage =====
FROM golang:1.23-alpine AS builder

# Install OS packages needed for building:
# - nodejs and npm: to install and run tailwindcss
# - ca-certificates: for HTTPS downloads
RUN apk add --no-cache nodejs npm ca-certificates

WORKDIR /app

# Here we assume templ is available via Go and install it into /go/bin.
RUN go install github.com/a-h/templ/cmd/templ@latest

# Download Go module dependencies first.
COPY go.mod go.sum ./
RUN go mod download

# Copy the rest of the project files.
COPY . .

# Install tailwindcss globally via npm.
RUN npm install tailwindcss @tailwindcss/cli

# Run the pre-build commands:
# 1. Process Tailwind CSS (from tailwind.css to static/tailwind.css)
# 2. Generate code/templates via templ.
#
# Note: Make sure the output directories (e.g. ./static) exist or are created by your tooling.
RUN npx @tailwindcss/cli -i ./tailwind.css -o ./static/tailwind.css --minify && \
    templ generate

# Ensure the output directory for the binary exists.
RUN mkdir -p bin

# Build the Go binary (matching the air.toml build command).
# Setting CGO_ENABLED=0 helps produce a statically linked binary.
ENV CGO_ENABLED=0 \
    GOOS=linux \
    GOARCH=amd64
RUN go build -o ./bin/main ./cmd/main.go

# ===== Final Stage =====
FROM alpine:latest

WORKDIR /app

# Copy the built binary from the builder stage.
COPY --from=builder /app/static ./static
COPY --from=builder /app/bin/main ./main

# (Optional) Expose the port your application listens on.
# EXPOSE 8080

# Run the binary.
CMD ["./main"]
