FROM node:14-alpine as base
ARG DATABASE_URL=postgresql://postgres:k0fpEoFJetxkObPD@localhost:5432/test
ENV TWILIO_SID=AC7
ENV TWILIO_AUTH_TOKEN=0
ENV SENDGRID_API_KEY=SG.
ENV APP_SECRET=test
ENV DATABASE_URL=$DATABASE_URL

#add required not in node-alpine
RUN apk add git

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

COPY package.json yarn.lock ./
COPY . .

# the produced image contains eveyrthing for testing
FROM base as generate
RUN yarn --frozen-lockfile
RUN yarn prisma generate

FROM generate as migration
RUN yarn db:up

FROM generate as prod
RUN yarn build
RUN cp -r api/templates .nexus/build/api
ENV NODE_ENV=production
CMD [ "node", ".nexus/build/api/index.js" ]

FROM prod as test
RUN apk add postgresql

RUN mkdir -p /run/postgresql/data \
    && chown postgres:postgres /run/postgresql/ \
    && su postgres -c 'initdb -D /var/lib/postgresql/data' \
    && echo "host all all 0.0.0.0/0 trust" >> /var/lib/postgresql/data/pg_hba.conf \
    && echo "listen_addresses='*'" >> /var/lib/postgresql/data/postgresql.conf \
    && su postgres -c 'pg_ctl start -D /var/lib/postgresql/data' \
    && yarn db:up -c \
    && yarn test


