# Build context MUST be the repo root:
#   docker build -f VigilCareRecordsAPI/Dockerfile -t vigilcare-records-api .
# Single-project solution today, but keeping the repo-root context matches the
# CI/CD guide's convention and avoids a context change if a shared library is
# ever extracted alongside VigilCareRecordsAPI.Tests.

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src

# Restore first with only the project file so the NuGet layer caches
# independently of source changes.
COPY VigilCareRecordsAPI/VigilCareRecordsAPI.csproj VigilCareRecordsAPI/
RUN dotnet restore VigilCareRecordsAPI/VigilCareRecordsAPI.csproj

COPY VigilCareRecordsAPI/ VigilCareRecordsAPI/
RUN dotnet publish VigilCareRecordsAPI/VigilCareRecordsAPI.csproj \
      -c Release -o /app/publish --no-restore

# Dev appsettings.json ships with placeholder secrets (Jwt:Secret, Minio:SecretKey).
# Blank them so a misconfigured production deploy fails fast instead of running
# with a known, publicly-committed secret.
RUN sed -i \
      -e 's/"Secret": "[^"]*"/"Secret": ""/' \
      -e 's/"SecretKey": "[^"]*"/"SecretKey": ""/' \
      /app/publish/appsettings.json

# ---- optional target: EF migration bundle (SDK stage). CD bakes migrate-bundle
# (scratch) and extracts via docker create + docker cp — never ship this stage. ----
FROM build AS migrate
RUN dotnet tool install --global dotnet-ef --version 8.*
ENV PATH="$PATH:/root/.dotnet/tools"
RUN dotnet ef migrations bundle \
      --project VigilCareRecordsAPI/VigilCareRecordsAPI.csproj \
      --self-contained -r linux-x64 \
      --output /out/migrate-api

# scratch + CMD so bare `docker create IMAGE` works (FROM scratch has no default cmd).
FROM scratch AS migrate-bundle
COPY --from=migrate /out/migrate-api /out/migrate-api
CMD ["/out/migrate-api"]

# ---- runtime (bake target "final") ----
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS final
WORKDIR /app

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

COPY --from=build /app/publish .

# aspnet:8.0 already ships non-root user `app` (UID/GID 1654).
RUN chown -R app:app /app
USER app

ENV ASPNETCORE_URLS=http://+:8080
EXPOSE 8080

# Liveness only (/health/live). Readiness is asserted by CD smoke (/health/ready).
# start-period covers process + Kestrel bind; migrate/seed no longer block listen.
HEALTHCHECK --interval=10s --timeout=5s --start-period=40s --retries=6 \
    CMD curl -fsS http://localhost:8080/health/live || exit 1

ENTRYPOINT ["dotnet", "VigilCareRecordsAPI.dll"]
