# backend/Dockerfile
FROM node:18-alpine

# Add build arguments
ARG NODE_ENV
ARG API_URL
ARG CORS_ORIGIN
ARG DATABASE_URL
ARG POSTGRES_USER
ARG POSTGRES_PASSWORD
ARG POSTGRES_DB
ARG JWT_SECRET
ARG SMTP_HOST
ARG SMTP_PORT
ARG SMTP_USER
ARG SMTP_PASS
ARG EMAIL_FROM
ARG DEFAULT_ADMIN_EMAIL
ARG DEFAULT_ADMIN_PASSWORD
ARG DEFAULT_ADMIN_NAME

# Set environment variables from build args
ENV NODE_ENV=${NODE_ENV}
ENV API_URL=${API_URL}
ENV CORS_ORIGIN=${CORS_ORIGIN}
ENV DATABASE_URL=${DATABASE_URL}
ENV POSTGRES_USER=${POSTGRES_USER}
ENV POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
ENV POSTGRES_DB=${POSTGRES_DB}
ENV JWT_SECRET=${JWT_SECRET}
ENV SMTP_HOST=${SMTP_HOST}
ENV SMTP_PORT=${SMTP_PORT}
ENV SMTP_USER=${SMTP_USER}
ENV SMTP_PASS=${SMTP_PASS}
ENV EMAIL_FROM=${EMAIL_FROM}
ENV DEFAULT_ADMIN_EMAIL=${DEFAULT_ADMIN_EMAIL}
ENV DEFAULT_ADMIN_PASSWORD=${DEFAULT_ADMIN_PASSWORD}
ENV DEFAULT_ADMIN_NAME=${DEFAULT_ADMIN_NAME}

WORKDIR /usr/src/app

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

# Copy package files
COPY package*.json ./
COPY prisma ./prisma/
# Install dependencies
RUN npm install --omit-dev

# Copy prisma schema
# COPY prisma ./prisma/

# Generate Prisma client
RUN npx prisma generate
# RUN npx prisma migrate deploy

# Copy source code
COPY . .

# Build the application
RUN npm run build

# Expose port
EXPOSE 3000

# ADD https://raw.githubusercontent.com/vishnubob/wait-for-it/master/wait-for-it.sh /wait-for-it.sh
# RUN chmod +x /wait-for-it.sh
# Add healthcheck
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD wget -q --spider http://localhost:3000/health || exit 1

# Start the application
# CMD ["npm", "run", "start:prod"]

CMD ["node", "dist/main.js"]
