FROM dart:stable AS build

WORKDIR /app

COPY pubspec.* ./
RUN dart pub get

COPY . .
RUN mkdir -p build \
    && dart compile exe bin/server.dart -o build/server \
    && dart compile exe bin/migrate.dart -o build/migrate

FROM debian:bookworm-slim AS runtime

RUN apt-get update \
    && apt-get install -y --no-install-recommends ca-certificates \
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app

ENV PORT=8080
ENV MIGRATE_ON_STARTUP=true

COPY --from=build /app/build/server /app/bin/server
COPY --from=build /app/build/migrate /app/bin/migrate
COPY migrations/ /app/migrations/
COPY scripts/docker-entrypoint.sh /app/scripts/docker-entrypoint.sh

RUN chmod +x /app/bin/server /app/bin/migrate /app/scripts/docker-entrypoint.sh

EXPOSE 8080

ENTRYPOINT ["/app/scripts/docker-entrypoint.sh"]
CMD ["/app/bin/server"]
