ARG USE_FRONTEND_BACKUP=false

# Build stage
FROM node:24-alpine AS builder

# Install pnpm
RUN corepack enable && corepack prepare pnpm@10 --activate

# Set working directory
WORKDIR /app

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

# Install backend dependencies
RUN pnpm install

# Copy source code and prisma schema
COPY . .

# Generate Prisma client
RUN pnpm db:generate

# Build TypeScript backend
RUN pnpm build

# Build frontend (or reuse compiled backup)
WORKDIR /app
ARG USE_FRONTEND_BACKUP
RUN if [ "$USE_FRONTEND_BACKUP" = "true" ]; then \
      rm -rf /app/frontend && mkdir -p /app/frontend && cp -R /app/frontend-backup/. /app/frontend/; \
    else \
      cd frontend-src && npm install && npm run build; \
    fi

# Create login.html from join.html if it doesn't exist
RUN if [ -f /app/frontend/join.html ] && [ ! -f /app/frontend/login.html ]; then \
      cp /app/frontend/join.html /app/frontend/login.html; \
    fi


# Production stage
FROM node:24-alpine

ARG USE_FRONTEND_BACKUP

# Install pnpm
RUN corepack enable && corepack prepare pnpm@10 --activate

# Set working directory
WORKDIR /app

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

# Install production dependencies only
RUN pnpm install --prod

# Copy prisma schema for migrations
COPY prisma ./prisma

# Generate Prisma client
RUN pnpm db:generate

# Copy built application from builder stage
COPY --from=builder /app/dist ./dist

# Copy built frontend from builder stage
COPY --from=builder /app/frontend ./frontend

# Expose port
EXPOSE 3000

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node -e "require('http').get('http://localhost:3000/api/v1/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"

# Start the application
CMD ["node", "dist/index.js"]
