# Use the official Node.js alpine image as builder
FROM node:20-alpine AS builder

WORKDIR /app

# Copy dependency files and install ALL dependencies (including devDependencies needed for build)
COPY package*.json ./
RUN npm ci

# Copy the rest of the application files
COPY . .

# Generate Prisma client
RUN npx prisma generate

# Build the frontend (Vite) and the server (Esbuild)
RUN npm run build

# Start a clean production runner stage
FROM node:20-alpine
WORKDIR /app

ENV NODE_ENV=production
ENV PORT=8080

# Copy package files and install only production dependencies
COPY package*.json ./
RUN npm ci --only=production

# Copy generated Prisma schema and client files
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma

# Copy built distribution (dist folder containing client assets and server.cjs)
COPY --from=builder /app/dist ./dist
# Copy index.html and assets if server looks for them in root (just in case)
COPY --from=builder /app/index.html ./index.html

# Expose port
EXPOSE 8080

# Command to start the application
CMD ["node", "dist/server.cjs"]
