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

# Copy solution and project files first for better layer caching
COPY RealCV.sln ./
COPY src/RealCV.Domain/RealCV.Domain.csproj src/RealCV.Domain/
COPY src/RealCV.Application/RealCV.Application.csproj src/RealCV.Application/
COPY src/RealCV.Infrastructure/RealCV.Infrastructure.csproj src/RealCV.Infrastructure/
COPY src/RealCV.Web/RealCV.Web.csproj src/RealCV.Web/

# Restore dependencies
RUN dotnet restore

# Copy all source code
COPY src/ src/

# Build and publish
WORKDIR /src/src/RealCV.Web
RUN dotnet publish -c Release -o /app/publish --no-restore

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

# Install curl for health checks
RUN apt-get update && apt-get install -y curl && rm -rf /var/lib/apt/lists/*

# Create non-root user for security
RUN groupadd -r realcv && useradd -r -g realcv realcv

# Copy published app
COPY --from=build /app/publish .

# Set ownership
RUN chown -R realcv:realcv /app

# Switch to non-root user
USER realcv

# Expose port
EXPOSE 8080

# Set environment variables
ENV ASPNETCORE_URLS=http://+:8080
ENV ASPNETCORE_ENVIRONMENT=Production
ENV DOTNET_RUNNING_IN_CONTAINER=true

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Start the app
ENTRYPOINT ["dotnet", "RealCV.Web.dll"]
