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

WORKDIR /app

COPY pubspec.yaml pubspec.lock ./
RUN flutter pub get

COPY . .

# Generate localizations (ARB -> Dart) before the main build.
RUN flutter gen-l10n

# Run tests
RUN flutter test

# Inject API base URL at build time via --dart-define.
# Default to same-origin /api to avoid mixed-content in HTTPS deployments.
ARG API_BASE_URL=/api
ARG SOURCE_MAPS=false
ARG WEB_RENDERER=auto
RUN set -eux; \
    build_args="--release --dart-define=API_BASE_URL=${API_BASE_URL}"; \
    if [ "${SOURCE_MAPS}" = "false" ]; then \
      build_args="${build_args} --no-source-maps"; \
    fi; \
    if [ "${WEB_RENDERER}" != "auto" ]; then \
      build_args="${build_args} --web-renderer=${WEB_RENDERER}"; \
    fi; \
    flutter build web ${build_args}

# Stage 2 – Serve with Caddy
FROM caddy:alpine AS runner

ARG PORT=5000
ENV PORT=${PORT}

COPY --from=builder /app/build/web /usr/share/caddy
COPY Caddyfile /etc/caddy/Caddyfile

EXPOSE ${PORT}
CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
