# Build stage
FROM node:22-alpine AS builder

WORKDIR /app

# Dependencies o'rnatish
COPY package*.json ./
RUN npm install --force

# Kodlarni nusxalash va build qilish
COPY . .

# Environment variables (agar kerak bo'lsa)
ENV NEXT_TELEMETRY_DISABLED=1

# Next.js static export
RUN npm run build

# Production stage - Nginx
FROM nginx:alpine

# Default html tozalaymiz
RUN rm -rf /usr/share/nginx/html/*

# ❗ MUHIM: Next.js static export - out papka
COPY --from=builder /app/out /usr/share/nginx/html

# Default nginx configni o'chiramiz
RUN rm /etc/nginx/conf.d/default.conf

# nginx.conf ni bevosita Dockerfile ichida yozamiz
RUN printf '%s\n' \
'server {' \
'    listen 80;' \
'    server_name _;' \
'' \
'    root /usr/share/nginx/html;' \
'    index index.html;' \
'' \
'    # Gzip compression' \
'    gzip on;' \
'    gzip_types text/plain text/css application/json application/javascript text/xml application/xml text/javascript;' \
'' \
'    # Cache static assets' \
'    location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {' \
'        expires 1y;' \
'        add_header Cache-Control "public, immutable";' \
'    }' \
'' \
'    # Next.js _next static files' \
'    location /_next/static/ {' \
'        expires 1y;' \
'        add_header Cache-Control "public, immutable";' \
'    }' \
'' \
'    # SPA routing - barcha requestlarni index.html ga yo'\''naltirish' \
'    location / {' \
'        try_files $uri $uri/ $uri.html /index.html;' \
'    }' \
'' \
'    # Security headers' \
'    add_header X-Frame-Options "SAMEORIGIN" always;' \
'    add_header X-Content-Type-Options "nosniff" always;' \
'    add_header X-XSS-Protection "1; mode=block" always;' \
'}' \
> /etc/nginx/conf.d/default.conf

EXPOSE 80

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