
# backend/Dockerfile
FROM node:18-alpine AS builder

WORKDIR /app

# Install necessary tools
RUN apk add --no-cache curl wget postgresql-client

# Copy package files
COPY package*.json ./

# Install dependencies including dev dependencies for building
RUN npm install

# Install NestJS CLI globally
RUN npm install -g @nestjs/cli

# Copy prisma files
COPY prisma ./prisma/

# Generate Prisma client
RUN npx prisma generate

# Copy source code
COPY . .

# Build the application
RUN npm run build

# Production stage
FROM node:18-alpine

WORKDIR /app

# Install necessary tools
RUN apk add --no-cache curl wget postgresql-client

# Copy package files
COPY package*.json ./

# Install production dependencies only
RUN npm install --omit=dev

# Copy prisma files and generate client
COPY prisma ./prisma/
RUN npx prisma generate

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

# Create the start script
RUN printf '#!/bin/sh\n\
    until pg_isready -h postgres -p 5432 -U ${POSTGRES_USER} -d ${POSTGRES_DB}; do\n\
    echo "Waiting for postgres..."\n\
    sleep 2\n\
    done\n\
    \n\
    echo "PostgreSQL is ready!"\n\
    \n\
    npx prisma migrate deploy\n\
    node dist/main.js\n' > /app/start.sh

# Make the script executable
RUN chmod +x /app/start.sh

EXPOSE 3000

# Use shell form to ensure environment variables are expanded
CMD ["/bin/sh", "/app/start.sh"]
