ARG FLUTTER_VERSION=3.29.3
ARG NGINX=1.25.2-alpine3.18-slim

# Stage 1 - Build Flutter Web on Debian
FROM debian:latest AS builder

# Install system dependencies
RUN apt-get update && \
    apt-get install -y \
    git \
    curl \
    unzip \
    xz-utils \
    libglu1-mesa \
    cmake \
    clang \
    ninja-build \
    pkg-config \
    && rm -rf /var/lib/apt/lists/*

# Install Flutter manually
RUN git clone https://github.com/flutter/flutter.git /usr/local/flutter
WORKDIR /usr/local/flutter
RUN git checkout stable

# Set Flutter environment
ENV PATH="$PATH:/usr/local/flutter/bin:/usr/local/flutter/bin/cache/dart-sdk/bin"
RUN flutter doctor -v
RUN flutter config --enable-web

# Copy app files
COPY . /app
WORKDIR /app

# Clean and get packages
RUN flutter clean
RUN flutter pub get
RUN flutter build web --release --output=build/tm_pwa

# Stage 2 - Runtime with NGINX
FROM nginx:${NGINX}

# Install runtime dependencies
RUN apk --no-cache add \
    curl \
    tzdata \
    ca-certificates \
    && mkdir -p /var/log/app \
    && chown nginx:nginx /var/log/app

# Copy build files from Debian builder
COPY --from=builder /app/build/tm_pwa /usr/tm/nginx/html

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]