FROM node:22-alpine AS builder

RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirror.de.velop.ir/alpine|g' /etc/apk/repositories
RUN apk add --no-cache tzdata
RUN npm install -g pnpm@10

RUN cp /usr/share/zoneinfo/Asia/Tehran /etc/localtime && echo "Asia/Tehran" > /etc/timezone

WORKDIR /build

ARG VITE_TOKEN_NAME
ARG VITE_REFRESH_TOKEN_NAME
ARG VITE_DANAK_BASE_URL
ARG VITE_BASE_URL
ARG VITE_SERVICE_ID
ARG VITE_LOGIN_URL
ARG VITE_CONSOLE_URL
ARG VITE_WORKSPACE_ID
ARG VITE_HELP_URL

COPY package*.json pnpm-lock.yaml ./

RUN sh -c '\
  pnpm config set registry https://package-mirror.liara.ir/repository/npm/ && \
  pnpm install --frozen-lockfile --loglevel info \
  || \
  (echo "Liara mirror failed, falling back to npmjs..." && \
   pnpm config set registry https://registry.npmjs.org/ && \
   pnpm install --frozen-lockfile --loglevel info)'

COPY . ./

RUN set -e; \
  env_args=""; \
  [ -n "$VITE_TOKEN_NAME" ] && env_args="$env_args VITE_TOKEN_NAME=$VITE_TOKEN_NAME"; \
  [ -n "$VITE_REFRESH_TOKEN_NAME" ] && env_args="$env_args VITE_REFRESH_TOKEN_NAME=$VITE_REFRESH_TOKEN_NAME"; \
  [ -n "$VITE_DANAK_BASE_URL" ] && env_args="$env_args VITE_DANAK_BASE_URL=$VITE_DANAK_BASE_URL"; \
  [ -n "$VITE_BASE_URL" ] && env_args="$env_args VITE_BASE_URL=$VITE_BASE_URL"; \
  [ -n "$VITE_SERVICE_ID" ] && env_args="$env_args VITE_SERVICE_ID=$VITE_SERVICE_ID"; \
  [ -n "$VITE_LOGIN_URL" ] && env_args="$env_args VITE_LOGIN_URL=$VITE_LOGIN_URL"; \
  [ -n "$VITE_CONSOLE_URL" ] && env_args="$env_args VITE_CONSOLE_URL=$VITE_CONSOLE_URL"; \
  [ -n "$VITE_WORKSPACE_ID" ] && env_args="$env_args VITE_WORKSPACE_ID=$VITE_WORKSPACE_ID"; \
  [ -n "$VITE_HELP_URL" ] && env_args="$env_args VITE_HELP_URL=$VITE_HELP_URL"; \
  eval "env$env_args pnpm run build"

FROM nginx:stable-alpine AS production-stage

RUN sed -i 's|https://dl-cdn.alpinelinux.org/alpine|https://mirror.de.velop.ir/alpine|g' /etc/apk/repositories

COPY --from=builder /build/dist /usr/share/nginx/html
COPY --from=builder /build/nginx.con[f] /etc/nginx/conf.d/default.conf

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