version: '3.8'

services:
  # Frontend React application
  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    ports:
      - "3000:3000"
    volumes:
      - ./frontend:/app
      - /app/node_modules
    depends_on:
      - backend
    networks:
      - app-network

  # Backend Express server
  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    env_file:
      - ./backend/.env
    ports:
      - "${PORT:-4000}:4000"
    volumes:
      - ./backend:/app
      - /app/node_modules
      - ./backend/public/uploads:/app/public/uploads # Persist uploads
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
        required: false
    networks:
      - app-network

  # PostgreSQL Database
  db:
    image: postgres:14-alpine
    ports:
      - "5432:5432"
    volumes:
      - postgres_data:/var/lib/postgresql/data
      - ./db/init:/docker-entrypoint-initdb.d
    env_file:
      - ./backend/.env
    restart: always
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 5s
      retries: 5
      start_period: 10s
    networks:
      - app-network

  # Redis service - only active in cloud mode
  redis:
    image: redis:alpine
    command: ["sh", "-c", "redis-server ${REDIS_PASSWORD:+--requirepass $REDIS_PASSWORD}"]
    volumes:
      - redis_data:/data
    networks:
      - app-network
    profiles:
      - cloud
    healthcheck:
      test: ["CMD", "redis-cli", "${REDIS_PASSWORD:+--pass}", "${REDIS_PASSWORD}", "ping"]
      interval: 5s
      timeout: 5s
      retries: 5

  # Background worker for SQS and job processing - only active in cloud mode
  worker:
    build:
      context: ./backend
      dockerfile: Dockerfile
    command: node src/worker.js
    env_file:
      - ./backend/.env
    environment:
      - WORKER_MODE=true
    volumes:
      - ./backend:/app
      - /app/node_modules
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
        required: false
    networks:
      - app-network
    profiles:
      - cloud
    restart: always

volumes:
  postgres_data:
  redis_data:

networks:
  app-network:
    driver: bridge