FROM node:24.4-alpine3.21 AS build
WORKDIR /app

RUN apk update && apk add bash curl

# Copy package files first for better caching
COPY frontend/package.json frontend/yarn.lock ./

ARG NODE_ENV

# Install dependencies
RUN if [ "$NODE_ENV" = "development" ]; \
      then yarn install; \
      else yarn install --production=false; \
      fi

# Copy source files - we'll handle development overrides through volumes
COPY frontend ./

RUN rm -rf ./src/shared

# Now copy the actual shared folder - be explicit with the path
COPY backend/src/shared/ ./src/shared/

# Build only in production
RUN if [ "$NODE_ENV" == "production" ]; then \
      yarn run build; \
      fi

# Ports
ENV PORT 8081
EXPOSE $PORT

# Add development target
FROM build AS development
CMD ["yarn", "run", "dev"]

# ----------------------------------------------------------------
# 2. production stage
# Here we will use a new docker image, which is only the web backend
FROM nginx:stable-alpine AS production
WORKDIR /app

# Copy nginx config as a template
COPY frontend/provision/nginx.conf /etc/nginx/conf.d/default.conf.template

COPY --from=build app/dist /usr/share/nginx/html
COPY frontend/provision/entrypoint.sh /docker-entrypoint.d/entrypoint.sh

# Make sure the entrypoint is executable
RUN chmod +x /docker-entrypoint.d/entrypoint.sh

ENV PORT 80
EXPOSE $PORT

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