# مرحله ۱: Build با caching بهتر
FROM mcr.microsoft.com/dotnet/sdk:9.0 AS build
WORKDIR /src

# نصب dependencyها (apt-get) در یک layer
RUN apt-get update && apt-get install -y python3 make cmake clang zlib1g-dev \
    && rm -rf /var/lib/apt/lists/*

# کپی csprojها جداگانه برای cache بهتر
COPY TaxPayerFull/Front.csproj Front/
COPY Shared/Shared.csproj Shared/

# نصب wasm-tools (فقط اگر تغییر کند cache می‌ماند)
RUN dotnet workload install wasm-tools

# restore تنها بر اساس csprojها
RUN dotnet restore Front/Front.csproj

# کپی باقی پروژه
COPY TaxPayerFull/. TaxPayerFull/
COPY Shared/. Shared/

# انتشار Blazor WASM
RUN dotnet publish "TaxPayerFull/Front.csproj" -c Release -o /app \
    -p:TreatWarningsAsErrors=false \
    -p:RunAOTCompilation=false \
    -p:PublishTrimmed=false

# مرحله ۲: Nginx
FROM nginx:alpine AS final
WORKDIR /usr/share/nginx/html
RUN rm -rf ./*

COPY --from=build /app/wwwroot ./

# کانفیگ Nginx
RUN printf 'server {\n\
    listen       5107;\n\
    server_name  localhost;\n\
    root /usr/share/nginx/html;\n\
    index index.html;\n\
\n\
    location / {\n\
        try_files $uri $uri/ /index.html;\n\
    }\n\
\n\
    location /_framework/ {\n\
        expires 1y;\n\
        add_header Cache-Control "public, immutable";\n\
    }\n\
    location /_content/ {\n\
        expires 1y;\n\
        add_header Cache-Control "public, immutable";\n\
    }\n\
    location /assets/ {\n\
        expires 7d;\n\
        add_header Cache-Control "public";\n\
    }\n\
    location /css/ { expires 7d; add_header Cache-Control "public"; }\n\
    location /fonts/ { expires 7d; add_header Cache-Control "public"; }\n\
    location /img/ { expires 7d; add_header Cache-Control "public"; }\n\
    location /js/ { expires 7d; add_header Cache-Control "public"; }\n\
\n\
    location ~ \\.dll$ { add_header Content-Type application/octet-stream; }\n\
    location ~ \\.wasm$ { add_header Content-Type application/wasm; }\n\
    location ~ \\.pdb$ { add_header Content-Type application/octet-stream; }\n\
    location ~ \\.dat$ { add_header Content-Type application/octet-stream; }\n\
\n\
    gzip on;\n\
    gzip_types text/plain application/xml text/css application/javascript application/json application/wasm;\n\
    gzip_min_length 256;\n\
\n\
    error_page 404 /index.html;\n\
}' > /etc/nginx/conf.d/default.conf

EXPOSE 5107
CMD ["nginx", "-g", "daemon off;"]
