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

# Restore layer — copy only project files so NuGet restore is cached
# independently of source changes. ProjectReferences must be present.
COPY VigilCareClinical.sln ./
COPY VigilCare.ClinicalContracts/VigilCare.ClinicalContracts.csproj VigilCare.ClinicalContracts/
COPY VigilCare.Simulation.Core/VigilCare.Simulation.Core.csproj VigilCare.Simulation.Core/
COPY VigilCareClinicalAPI/VigilCareClinicalAPI.csproj VigilCareClinicalAPI/
RUN dotnet restore VigilCareClinicalAPI/VigilCareClinicalAPI.csproj

COPY VigilCare.ClinicalContracts/ VigilCare.ClinicalContracts/
COPY VigilCare.Simulation.Core/ VigilCare.Simulation.Core/
COPY VigilCareClinicalAPI/ VigilCareClinicalAPI/
RUN dotnet publish VigilCareClinicalAPI/VigilCareClinicalAPI.csproj \
    -c Release -o /app/publish --no-restore

# Scrub development secrets from the published appsettings.json (Step 4).
# Production supplies Jwt / PHI / API keys via environment variables only.
RUN sed -i \
      -e 's/"SigningKey": "[^"]*"/"SigningKey": ""/' \
      -e 's/"SearchTokenKey": "[^"]*"/"SearchTokenKey": ""/' \
      -e 's/"Gateway": "dev-[^"]*"/"Gateway": ""/' \
      -e 's/"ApiKey": "dev-integration[^"]*"/"ApiKey": ""/' \
      /app/publish/appsettings.json

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
WORKDIR /app

# curl is required by the container healthcheck; the aspnet image does not ship it.
RUN apt-get update \
 && apt-get install -y --no-install-recommends curl \
 && rm -rf /var/lib/apt/lists/*

COPY --from=build /app/publish .

# The keyring directory must be owned by the runtime user — see Step 10.
# The aspnet:8.0 image ships a non-root `app` user (uid 1654).
RUN mkdir -p /app/data-protection-keys && chown -R app:app /app
USER app

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

HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
  CMD curl -fsS http://localhost:8080/health/live || exit 1

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