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 — used as the certificate CN and read by the app via Hsts:Domain config
ENV Hsts__Domain=nas.oneputleygreen.com

# Generate a self-signed TLS certificate for HTTPS
RUN mkdir -p /app/certs && \
    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}" && \
    openssl pkcs12 -export \
        -out /app/certs/cert.pfx \
        -inkey /app/certs/key.pem \
        -in /app/certs/cert.pem \
        -passout pass: && \
    rm /app/certs/key.pem /app/certs/cert.pem

# 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.pfx
ENV ASPNETCORE_Kestrel__Certificates__Default__Password=""

# 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"]
