# 多阶段构建 Dockerfile
# 第一阶段：构建前端
FROM node:20-slim AS frontend-build

WORKDIR /app/frontend

# 复制前端项目文件
COPY Web/package.json Web/pnpm-lock.yaml ./
RUN npm install -g pnpm && pnpm install

# 复制前端源代码并构建
COPY Web/ ./
RUN pnpm run build

# 第二阶段：构建后端
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS backend-build

# 禁用遥测和减少并行度以尝试修复 exit code 134 (常见于内存受限环境下的崩溃)
ENV DOTNET_CLI_TELEMETRY_OPTOUT=1 \
    DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1

WORKDIR /app

# 复制解决方案文件和项目文件
COPY *.sln ./
COPY Directory.Build.props ./
COPY Directory.Packages.props ./
COPY nuget.config ./
COPY Common/*.csproj ./Common/
COPY Entity/*.csproj ./Entity/
COPY Repository/*.csproj ./Repository/
COPY Service/*.csproj ./Service/
COPY WebApi/*.csproj ./WebApi/
COPY WebApi.Test/*.csproj ./WebApi.Test/

# 还原依赖
RUN dotnet restore

# 复制所有源代码
COPY Common/ ./Common/
COPY Entity/ ./Entity/
COPY Repository/ ./Repository/
COPY Service/ ./Service/
COPY WebApi/ ./WebApi/

# 构建并发布
# 使用 -m:1 限制 CPU/内存并行度，减少容器构建崩溃风险
RUN dotnet publish WebApi/WebApi.csproj -c Release -o /app/publish --no-restore -m:1

# 将前端构建产物复制到后端的 wwwroot 目录
COPY --from=frontend-build /app/frontend/dist /app/publish/wwwroot

# 第三阶段：运行时镜像
FROM mcr.microsoft.com/dotnet/aspnet:10.0 AS runtime

WORKDIR /app

# 复制发布的应用
COPY --from=backend-build /app/publish ./

# 创建数据库目录
RUN mkdir -p /app/database

# 暴露端口
EXPOSE 8080

# 设置环境变量
ENV ASPNETCORE_URLS=http://+:8080
ENV ASPNETCORE_ENVIRONMENT=Production

# 启动应用
ENTRYPOINT ["dotnet", "WebApi.dll"]
