FROM crystallang/crystal:1.9.2-alpine AS builder

# Install build dependencies
RUN apk add --no-cache \
    yaml-dev \
    openssl-dev \
    zlib-dev \
    sqlite-dev \
    postgresql-dev

WORKDIR /app

# Copy shard files and install dependencies
COPY shard.yml shard.lock ./
RUN shards install --production

# Copy source code
COPY src/ ./src/

# Build the binary
RUN crystal build --release --static src/web/app.cr -o web-portal

# Runtime stage
FROM alpine:3.19

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

WORKDIR /app

# Copy the binary from builder
COPY --from=builder /app/web-portal .

# Copy views and static files
COPY --from=builder /app/src/web/views ./src/web/views
COPY public ./public

# Create non-root user
RUN adduser -D webuser && \
    chown -R webuser:webuser /app

USER webuser

# Set environment variables
ENV PORT=3000
ENV KEMAL_ENV=production

# Expose ports
EXPOSE 3000

ENTRYPOINT ["/app/web-portal"]
