FROM node:20-alpine

WORKDIR /app

# Install system dependencies
RUN apk add --no-cache python3 build-base g++ make sqlite

# Install pnpm
RUN npm install -g pnpm

# Copy package files
COPY package.json pnpm-lock.yaml ./

# Install dependencies with native bindings build approval
RUN pnpm install --unsafe-perm --no-optional --frozen-lockfile
RUN pnpm rebuild better-sqlite3

# Copy source code
COPY . .

# Create database directory
RUN mkdir -p db/

# Expose the port
EXPOSE 3000

# Startup script to migrate DB and start app
RUN echo '#!/bin/sh \n\
mkdir -p /app/db \n\
pnpm db:migrate || echo "Migration failed, continuing anyway" \n\
pnpm start' > /app/startup.sh && chmod +x /app/startup.sh

# Start the application
CMD ["/app/startup.sh"]