# Build stage
FROM oven/bun:1 AS builder
WORKDIR /usr/src/app

# Install dependencies
COPY package.json bun.lock ./
RUN bun install --frozen-lockfile

# Copy source code and content
COPY . .

# Copy database initialization script
COPY init-db.ts ./

# Initialize database using init-db.ts script
# This script handles draft-aware post verification and stability detection
ENV NODE_ENV=build
RUN bun run init-db.ts

# Final production stage
FROM oven/bun:1
WORKDIR /usr/src/app

# Copy dependencies
COPY --from=builder /usr/src/app/node_modules ./node_modules
COPY --from=builder /usr/src/app/package.json ./

# Copy source code (for runtime transpilation)
COPY --from=builder /usr/src/app/src ./src
COPY --from=builder /usr/src/app/content ./content
COPY --from=builder /usr/src/app/bun_plugins ./bun_plugins
COPY --from=builder /usr/src/app/index.tsx .
COPY --from=builder /usr/src/app/tsconfig.json .

# Copy the initialized database for efficient layer caching
COPY --from=builder /usr/src/app/blog.sqlite ./

# Fix ownership for bun user (needed for runtime operations)
RUN chown -R bun:bun /usr/src/app

# Switch to bun user
USER bun

# Expose the default port
EXPOSE 3000/tcp

# Production environment (onStartup-post-importer won't run since DB exists)
ENV NODE_ENV=production

# Run the application directly (Bun handles TSX transpilation at runtime)
ENTRYPOINT [ "bun", "run", "index.tsx" ]
