# ---------- Build stage ----------
FROM node:20-alpine AS build
WORKDIR /app

# Install dependencies first for better layer caching.
COPY package.json package-lock.json* ./
RUN npm ci || npm install

COPY . .
RUN npm run build

# ---------- Serve stage ----------
FROM nginx:alpine AS final

# OpenSSL is used to generate a self-signed certificate so HTTPS works out of the box.
RUN apk add --no-cache openssl && \
    mkdir -p /etc/nginx/certs && \
    openssl req -x509 -nodes -newkey rsa:2048 -days 365 \
        -keyout /etc/nginx/certs/server.key \
        -out /etc/nginx/certs/server.crt \
        -subj "/CN=dailymeals.local" && \
    chmod 600 /etc/nginx/certs/server.key

COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /app/dist /usr/share/nginx/html

EXPOSE 80 443

HEALTHCHECK --interval=30s --timeout=5s --retries=3 \
    CMD wget --no-verbose --no-check-certificate --tries=1 --spider https://localhost/ || exit 1

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