# ============================================
# Stage 1: Build Flutter Web Application
# ============================================
FROM ghcr.io/cirruslabs/flutter:stable AS builder

USER root

WORKDIR /app

# Safe directory configuration for git
RUN git config --global --add safe.directory /app

# Enable web support (idempotent)
RUN flutter config --enable-web

# Copy dependency files first for better caching
# Note: pubspec.lock will be generated by flutter pub get if missing
COPY pubspec.yaml ./

# Get dependencies (generates pubspec.lock automatically)
RUN flutter pub get

# Copy source code
COPY . .

# Re-run pub get after copying source to ensure lockfile consistency
RUN flutter pub get

# Build web application (CanvasKit renderer is now default)
RUN flutter build web --release --verbose

# ============================================
# Stage 2: Serve with dhttpd (Dart HTTP server)
# ============================================
FROM dart:stable

WORKDIR /app

# Install dhttpd globally
RUN dart pub global activate dhttpd

# Copy built web application from builder stage
COPY --from=builder /app/build/web /app/web

# Expose port (internal only, not mapped to host)
EXPOSE 8089

# Serve web application
CMD ["/root/.pub-cache/bin/dhttpd", "--host", "0.0.0.0", "--port", "8089", "--path", "/app/web"]
