FROM node:22-alpine AS deps

RUN apk add --no-cache python3 make g++ sqlite git

WORKDIR /app

# Clone full emdash monorepo (with patch applied)
RUN git clone --depth=1 https://git.moreminimore.com/kunthawat/emdash-patch-imageupload.git emdash

# Clone blog template source
RUN git clone --depth=1 https://git.moreminimore.com/kunthawat/emdash-blog-template.git blog-template

WORKDIR /app/emdash

# Add blog template as workspace package and install all deps
RUN cp -r /app/blog-template packages/blog-template
RUN corepack enable && corepack prepare pnpm@9.0.0 --activate
RUN pnpm install

# Build all packages including the blog template
RUN cd packages/core && pnpm build
RUN cd packages/auth && pnpm build
RUN cd packages/blocks && pnpm install && pnpm build
RUN cd packages/admin && pnpm build
RUN cd packages/blog-template && pnpm build

FROM deps AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV HOST=0.0.0.0

# Copy from builder stage (not deps) - workspace root has all node_modules
COPY --from=builder /app/emdash/node_modules ./node_modules
COPY --from=builder /app/emdash/packages/blog-template/dist ./dist

EXPOSE 4321

COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]
