# Stage 1: Build Tailwind CSS
FROM node:20-slim AS tailwind-builder
WORKDIR /app

# Copy dependency manifests and install dependencies
COPY package.json package-lock.json ./
RUN npm ci

# Copy source, templates, and static directories for Tailwind compile scan
COPY src ./src
COPY templates ./templates
COPY static ./static

# Run Tailwind compilation
RUN npx tailwindcss -i src/input.css -o static/tailwind.css

# Stage 2: Build Rust application
FROM rust:1.95-slim AS builder
WORKDIR /app

# Create a dummy project to cache dependencies
RUN cargo new --bin stick
WORKDIR /app/stick

# Copy dependency manifests
COPY Cargo.toml Cargo.lock ./

# Build dependencies (cached as a layer unless Cargo.toml/Cargo.lock changes)
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/app/stick/target \
    cargo build

# Copy tailwind.css compiled in the first stage
COPY --from=tailwind-builder /app/static/tailwind.css ./static/tailwind.css

# Copy the actual source code, templates, and rest of static files
COPY src ./src
COPY templates ./templates
COPY static ./static
# Ensure the compiled tailwind.css is definitely the one used
COPY --from=tailwind-builder /app/static/tailwind.css ./static/tailwind.css

# Build the real binary
RUN --mount=type=cache,target=/usr/local/cargo/registry \
    --mount=type=cache,target=/app/stick/target \
    touch src/main.rs && \
    cargo build && \
    cp target/debug/stick /app/stick-bin

# Stage 3: Runtime stage
FROM debian:bookworm-slim
WORKDIR /app

# Install runtime dependencies if needed
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*

# Copy the binary and templates from the build stage
COPY --from=builder /app/stick-bin /app/stick
COPY --from=builder /app/stick/templates /app/templates

# Expose port 3007
EXPOSE 3007

# Set default HOST and PORT
ENV HOST=0.0.0.0
ENV PORT=3007

# Run the app
CMD ["/app/stick"]
