# ---------------------------------------------------------
# Builder stage
# ---------------------------------------------------------
FROM node:20-alpine AS builder
WORKDIR /app

COPY package*.json ./
RUN npm install

# FIX: Install TypeScript so "tsc" exists
RUN npm install -g typescript

COPY . .
RUN npm run build

# ---------------------------------------------------------
# Final runtime image
# ---------------------------------------------------------
FROM node:20-alpine
WORKDIR /app

# Install system packages needed for Postgres, Redis, Supervisor
RUN apk update && apk add --no-cache \
    supervisor \
    postgresql16 \
    postgresql16-client \
    redis \
    bash

# Create directories for Postgres, Redis, and Supervisor logs
RUN mkdir -p /var/lib/postgresql/data \
    && mkdir -p /var/lib/redis \
    && mkdir -p /var/log/supervisor

# FIX OWNERSHIP (required for Alpine Postgres + Redis to start)
RUN chown -R postgres:postgres /var/lib/postgresql \
    && chown -R redis:redis /var/lib/redis

# Copy built app from builder
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY package*.json ./

# Copy supervisor config
COPY supervisord.conf /etc/supervisor/conf.d/supervisord.conf

# Expose API port
EXPOSE 3333

# Start supervisor (which starts Postgres, Redis, API, Worker)
CMD ["/usr/bin/supervisord", "-n"]
