FROM mcr.microsoft.com/dotnet/aspnet:9.0 AS base

# Create a non-root user and group
ARG APP_UID=1000
ARG APP_GID=1000
RUN groupadd --gid $APP_GID appgroup && \
    useradd --uid $APP_UID --gid appgroup --create-home appuser

# Create data directory with correct ownership
RUN mkdir -p /app/blob-storage-data && \
    chown -R appuser:appgroup /app

WORKDIR /app
EXPOSE 8080
EXPOSE 8081

# Switch to non-root user
USER appuser

FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src

# Copy csproj files for all projects
COPY ["Femto.Api/Femto.Api.csproj", "Femto.Api/"]
COPY ["Femto.Modules.Blog/Femto.Modules.Blog.csproj", "Femto.Modules.Blog/"]
COPY ["Femto.Common/Femto.Common.csproj", "Femto.Common/"]
COPY ["Femto.Modules.Auth.Contracts/Femto.Modules.Auth.Contracts.csproj", "Femto.Modules.Auth.Contracts/"]
COPY ["Femto.Modules.Auth/Femto.Modules.Auth.csproj", "Femto.Modules.Auth/"]
COPY ["Femto.Modules.Media/Femto.Modules.Media.csproj", "Femto.Modules.Media/"]
COPY ["Femto.Database/Femto.Database.csproj", "Femto.Database/"]

# Restore all dependencies
RUN dotnet restore "Femto.Api/Femto.Api.csproj"

# Copy everything
COPY . .

# Build the API
WORKDIR "/src/Femto.Api"
RUN dotnet build "Femto.Api.csproj" -c $BUILD_CONFIGURATION -o /app/build

# Build and publish both API and Database CLI
FROM build AS publish
ARG BUILD_CONFIGURATION=Release

# Publish API
RUN dotnet publish "Femto.Api.csproj" -c $BUILD_CONFIGURATION -o /app/publish /p:UseAppHost=false

# Publish Database CLI
WORKDIR "/src/Femto.Database"
RUN dotnet publish "Femto.Database.csproj" -c $BUILD_CONFIGURATION -o /app/femto-db /p:UseAppHost=false

# Final runtime image
FROM base AS final
WORKDIR /app

# Copy published API and DB CLI
COPY --from=publish /app/publish .
COPY --from=publish /app/femto-db /app/femto-db

# Add a wrapper script to launch the DB CLI
RUN mkdir -p /app/scripts && \
    echo '#!/bin/sh\nexec dotnet /app/femto-db/Femto.Database.dll "$@"' > /app/scripts/femto-db && \
    chmod +x /app/scripts/femto-db

# Optional: add script dir to PATH for easier access
ENV PATH="/app/scripts:${PATH}"

# This envvar is used by Femto.Database up to load the migrations
ENV MigrationsDirectory='/app/femto-db/Migrations'

# Entrypoint for the API
ENTRYPOINT ["dotnet", "Femto.Api.dll"]
