# Stage 1: Build frontend
FROM node:22-alpine AS frontend-build

WORKDIR /app/web

# Install pnpm
RUN corepack enable && corepack prepare pnpm@latest --activate

# Copy frontend package files
COPY web/package.json web/pnpm-lock.yaml web/pnpm-workspace.yaml ./

# Install dependencies
RUN pnpm install --frozen-lockfile

# Copy frontend source
COPY web/ ./

# Build frontend
RUN pnpm build

# Stage 2: Build backend
FROM dart:stable AS backend-build

WORKDIR /app

# Resolve app dependencies
COPY pubspec.* ./
RUN dart pub get

# Copy app source code and compile
COPY bin/ ./bin/
COPY --from=frontend-build /app/web/build ./web/build/

RUN dart compile exe bin/server.dart -o bin/server

# Stage 3: Runtime image with libvips
FROM debian:bookworm-slim AS runtime

# Install libvips and ca-certificates
RUN apt-get update && apt-get install -y --no-install-recommends \
    libvips42 \
    ca-certificates \
    curl \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy the AOT runtime and compiled server from build stage
COPY --from=backend-build /runtime/ /
COPY --from=backend-build /app/bin/server /app/bin/
COPY --from=backend-build /app/web/build /app/web/build

# Create data and cache directories
RUN mkdir -p /app/data /app/cache

# Set environment variables (can be overridden at runtime)
ENV PORT=8080 \
    DATA_DIR=/app/data \
    CACHE_DIR=/app/cache

# Expose port
EXPOSE 8080

# Start server
CMD ["/app/bin/server"]