# ----- Build deps -----
FROM node:22-alpine AS deps

WORKDIR /app

COPY package.json package-lock.json starwind-*.tgz ./
RUN npm ci

# ----- Build -----
FROM node:22-alpine AS build

WORKDIR /app

COPY --from=deps /app/node_modules ./node_modules
COPY package.json package-lock.json starwind-*.tgz ./
COPY astro.config.* ./
COPY tsconfig.json ./
COPY src ./src
COPY public ./public

ENV NODE_ENV=production
RUN npm run build

# ----- Production deps -----
FROM node:22-alpine AS prod-deps

WORKDIR /app

COPY package.json package-lock.json starwind-*.tgz ./
RUN npm ci --omit=dev

# ----- Runtime -----
FROM node:22-alpine AS runtime

WORKDIR /app

ENV NODE_ENV=production
ENV HOST=0.0.0.0
ENV PORT=4321

COPY --from=prod-deps /app/node_modules ./node_modules
COPY --from=build /app/dist ./dist

USER node

EXPOSE 4321

HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \
  CMD node -e "require('http').get({host:'127.0.0.1',port:process.env.PORT||4321,path:'/api/healthz'},(r)=>process.exit((r.statusCode||500)<500?0:1)).on('error',()=>process.exit(1))"

CMD ["node", "./dist/server/entry.mjs"]
