# Stage 1: Build Flutter web application
FROM ghcr.io/cirruslabs/flutter:stable AS builder

WORKDIR /app

# Copy dependency files first for better caching
COPY pubspec.yaml ./

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

# Copy the rest of the application
COPY . .

# Generate code with build_runner
RUN dart run build_runner build --delete-conflicting-outputs

# Generate health.json with version info
RUN dart run tool/generate_health_json.dart

# Build for web release with production configuration
# These URLs enable authentication (requiresAuth = true when URL contains schweitz.net)
RUN flutter build web --release \
    --dart-define=CORE_API_URL=https://api.schweitz.net \
    --dart-define=TATLOCK_API_URL=https://tatlock.schweitz.net

# Stage 2: Serve with nginx
FROM nginx:alpine

# Install curl for healthcheck
RUN apk add --no-cache curl

# Copy custom nginx configuration
COPY nginx.conf /etc/nginx/nginx.conf

# Copy built web app to nginx html directory
COPY --from=builder /app/build/web /usr/share/nginx/html

# Expose port 80
EXPOSE 80

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:80/ || exit 1

# Run nginx in foreground
CMD ["nginx", "-g", "daemon off;"]
