# Build stage for Go backend
FROM golang:1.23-alpine AS backend-builder

WORKDIR /app

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

# Copy go mod files
COPY go.mod go.sum ./
RUN go mod download

# Copy source code
COPY . .

# Build backend
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /go-first ./cmd/server

# Build stage for React frontend
FROM node:20-alpine AS frontend-builder

WORKDIR /web

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

# Copy source and build
COPY web/ ./
RUN npm run build

# Final stage
FROM alpine:3.20

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

# Create non-root user
RUN addgroup -g 1000 -S appgroup && \
    adduser -u 1000 -S appuser -G appgroup

WORKDIR /app

# Copy backend binary
COPY --from=backend-builder /go-first .

# Copy frontend build
COPY --from=frontend-builder /web/dist ./web/dist

# Copy config and the project catalog used as the initial import.
COPY config.yaml .
COPY projects.json .

# Create directories for uploads, logs, etc.
RUN mkdir -p /app/uploads /app/logs && \
    chown -R appuser:appgroup /app

USER appuser

# Expose port
EXPOSE 8080

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:8080/api/v1/health || exit 1

# Run
ENTRYPOINT ["./go-first"]