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

COPY package.json package-lock.json* ./
RUN npm ci || npm install

COPY . .
RUN npm run build

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

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/meal-plan-frontend-angular/browser /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;"]
