# 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

# Build for web release
RUN flutter build web --release

# 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;"]
