FROM mcr.microsoft.com/dotnet/aspnet:10.0-preview AS base
RUN apt-get update && apt-get upgrade -y && apt-get install -y openssl && rm -rf /var/lib/apt/lists/*
WORKDIR /app
EXPOSE 8080
EXPOSE 8443

FROM mcr.microsoft.com/dotnet/sdk:10.0-preview AS build
WORKDIR /src

# Copy project files first so the restore layer is cached independently of source changes
COPY BudgetApp.Data/BudgetApp.Data.csproj BudgetApp.Data/
COPY BudgetApp/BudgetApp.csproj BudgetApp/
RUN dotnet restore BudgetApp/BudgetApp.csproj

# Copy all source (BudgetApp.Data must be present before building BudgetApp)
COPY BudgetApp.Data/ BudgetApp.Data/
COPY BudgetApp/ BudgetApp/

WORKDIR /src/BudgetApp
RUN dotnet publish -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .

LABEL org.opencontainers.image.title="Budgeteer" \
      org.opencontainers.image.description="A personal finance dashboard built with Blazor Server (.NET 10). Multi-account support, recurring transactions, category management, balance trend charts, and ASP.NET Identity authentication." \
      org.opencontainers.image.url="https://github.com/edgeofsanity76/Budgeteer" \
      org.opencontainers.image.source="https://github.com/edgeofsanity76/Budgeteer" \
      org.opencontainers.image.licenses="MIT"

# Ensure the SQLite data directory exists and is writable
RUN mkdir -p /app/data

# HSTS domain — read by the app via Hsts:Domain config
ENV Hsts__Domain=nas.oneputleygreen.com

# Copy the SSL certificate (CN=nas.oneputleygreen.com).
# Place cert.pem and key.pem in certs/ before building — excluded from git via certs/* in .gitignore.
# If cert.pem is absent (e.g. CI builds) a self-signed fallback is generated automatically.
COPY certs/ /app/certs/
RUN if [ ! -f /app/certs/cert.pem ]; then \
        echo "No cert.pem found — generating self-signed certificate for ${Hsts__Domain}" && \
        openssl req -x509 -newkey rsa:4096 \
            -keyout /app/certs/key.pem \
            -out /app/certs/cert.pem \
            -days 3650 \
            -nodes \
            -subj "/C=GB/ST=England/O=Budgeteer/CN=${Hsts__Domain}"; \
    fi

# Serve on both HTTP and HTTPS
ENV ASPNETCORE_HTTP_PORTS=8181
ENV ASPNETCORE_HTTPS_PORTS=8282
ENV ASPNETCORE_Kestrel__Certificates__Default__Path=/app/certs/cert.pem
ENV ASPNETCORE_Kestrel__Certificates__Default__KeyPath=/app/certs/key.pem

# Store the database in the volume-mountable /app/data directory
ENV ConnectionStrings__DefaultConnection="Data Source=/app/data/budgetapp.db"

# SSO / OAuth provider configuration (override at runtime with your credentials)
ENV Authentication__Google__ClientId="" \
    Authentication__Google__ClientSecret="" \
    Authentication__Microsoft__ClientId="" \
    Authentication__Microsoft__ClientSecret="" \
    Authentication__Facebook__ClientId="" \
    Authentication__Facebook__ClientSecret=""

VOLUME ["/app/data"]

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