# 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, built and extracted by the CD
# migrate job (docker build --target migrate + docker cp). Never shipped in the
# runtime image below. ----
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

# ---- runtime ----
FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS runtime
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

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

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