version: '3.8'

services:
  nxweb:
    image: nexgendev/nxweb-core:${BUILD:-latest}  # ✅ ใช้ Image ที่ Build แล้ว
    user: "${UID:-1000}:${GID:-1000}"
    container_name: nxweb-core
    ports:
      - "9090:80"
    volumes:
      - ./app/content:/var/www/docroot/sites/default:delegated
      - ./app/libraries:/var/www/docroot/libraries
    depends_on:
      - db
    env_file: 
      - .env 
    environment:
      - APP_ENV=${APP_ENV:-prod}
      - DATABASE_URL=pgsql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}
      - PATH=/var/www/bin:/var/www/vendor/drush/drush:${PATH}
    healthcheck:
      test: ["CMD", "curl", "-f", "-L", "http://localhost/core/install.php"]
      interval: 30s
      timeout: 10s
      retries: 3
      start_period: 10s
    restart: unless-stopped
    entrypoint: >
      sh -c "
        if [ ! -d '/var/www/docroot/sites/default/files' ]; then
          mkdir -p /var/www/docroot/sites/default/files &&
          chown -R ${UID}:www-data /var/www/docroot/sites/default/files &&
          chmod -R 775 /var/www/docroot/sites/default/files;
        else
          echo 'Directory already exists, skipping creation';
        fi
        exec apache2-foreground
      "

  db:
    image: postgres:latest
    container_name: postgres-db
    user: "root:${GID:-1000}"
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-default}
      POSTGRES_USER: ${POSTGRES_USER:-nxuser}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-nxpass}
    volumes:
      - ./app/postgres:/var/lib/postgresql/data
      - ./export:/var/lib/postgresql/export
    ports:
      - "5432:5432"
    command: [ "bash", "-c", "mkdir -p /var/lib/postgresql/export && chmod -R 777 /var/lib/postgresql/export && docker-entrypoint.sh postgres" ]
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 30s
      timeout: 10s
      retries: 5

  pgadmin:
    image: dpage/pgadmin4:latest
    container_name: pgadmin4
    env_file: 
      - .env
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-user@nxwebs.com}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-user}
    volumes:
      - ./server-configs/pgadmin4/servers.json:/pgadmin4/servers.json:ro
      - ./server-configs/pgadmin4/pgpass:/pgpass:ro
      - ./export:/var/lib/pgadmin/storage
    ports:
      - "9091:80"
    entrypoint: >
      sh -c "cp /pgadmin4/servers.json /var/lib/pgadmin/servers.json &&
            export PGPASSFILE=/pgpass &&
            /entrypoint.sh"
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost"]
      interval: 30s
      timeout: 10s
      retries: 3
    restart: unless-stopped