FROM node:24-alpine AS frontend-deps

WORKDIR /home/frontend/

COPY ./package.json ./package.json
COPY ./package-lock.json ./package-lock.json
COPY ./apps/calendars/package.json ./apps/calendars/package.json

RUN npm ci

COPY .dockerignore ./.dockerignore
# COPY ./.prettierrc.js ./.prettierrc.js
#COPY ./packages/eslint-config-calendars ./packages/eslint-config-calendars

COPY ./apps/calendars ./apps/calendars

# Build open-calendar package

WORKDIR /home/frontend

### ---- Front-end builder image ----
FROM frontend-deps AS calendars

WORKDIR /home/frontend/apps/calendars

FROM frontend-deps AS calendars-dev

WORKDIR /home/frontend

EXPOSE 3000

RUN cd apps/calendars && npm run build-theme

# Build open-calendar package if dist doesn't exist, then start dev server
CMD ["/bin/sh", "-c", "cd /home/frontend/apps/calendars && npm run dev"]

# Tilt will rebuild calendars target so, we dissociate calendars and calendars-builder
# to avoid rebuilding the app at every changes.
FROM calendars AS calendars-builder

WORKDIR /home/frontend/apps/calendars

ARG API_ORIGIN
ARG VISIO_BASE_URL
ARG GAUFRE_WIDGET_PATH
ARG GAUFRE_API_URL
ARG THEME_CSS_URL
ENV NEXT_PUBLIC_API_ORIGIN=${API_ORIGIN}
ENV NEXT_PUBLIC_VISIO_BASE_URL=${VISIO_BASE_URL}
ENV NEXT_PUBLIC_GAUFRE_WIDGET_PATH=${GAUFRE_WIDGET_PATH}
ENV NEXT_PUBLIC_GAUFRE_API_URL=${GAUFRE_API_URL}
ENV NEXT_PUBLIC_THEME_CSS_URL=${THEME_CSS_URL}

RUN npm run build-theme && npm run build

# ---- Front-end image ----
FROM caddy:2-alpine AS frontend-production

# Upgrade system packages to install security updates
RUN apk update && \
  apk upgrade && \
  rm -rf /var/cache/apk/*

COPY --from=calendars-builder \
  /home/frontend/apps/calendars/out \
  /srv

COPY ./Caddyfile /etc/caddy/Caddyfile

CMD ["caddy", "run", "--config", "/etc/caddy/Caddyfile", "--adapter", "caddyfile"]
