version: '3.8'

services:
  postgres:
    image: postgres:16-alpine
    container_name: postgres-main
    restart: unless-stopped
    networks:
      - database-internal
    env_file:
      - .env
    environment:
      POSTGRES_USER: ${POSTGRES_ADMIN_USER}
      POSTGRES_PASSWORD: ${POSTGRES_ADMIN_PASSWORD}
      POSTGRES_DB: postgres
      PGDATA: /var/lib/postgresql/data/pgdata
    volumes:
      - /mnt/psql-data:/var/lib/postgresql/data
      - ./init-scripts:/docker-entrypoint-initdb.d:ro
      - ./backups:/backups
    ports:
      - "127.0.0.1:5432:5432"
    command:
      - "postgres"
      - "-c"
      - "max_connections=200"
      - "-c"
      - "shared_buffers=2GB"
      - "-c"
      - "effective_cache_size=6GB"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_ADMIN_USER} -d postgres"]
      interval: 10s
      timeout: 5s
      retries: 5

  pgadmin:
    image: dpage/pgadmin4:latest
    container_name: pgadmin
    restart: unless-stopped
    networks:
      - database-internal
      - traefik-public
    env_file:
      - .env
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_PASSWORD}
      PGADMIN_CONFIG_SERVER_MODE: 'True'
    volumes:
      - pgadmin-data:/var/lib/pgadmin
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.pgadmin.rule=Host(`pgadmin.ai-impress.com`)"
      - "traefik.http.routers.pgadmin.entrypoints=websecure"
      - "traefik.http.routers.pgadmin.tls.certresolver=cloudflare"
      - "traefik.http.services.pgadmin.loadbalancer.server.port=80"
      - "traefik.http.routers.pgadmin.middlewares="
    depends_on:
      postgres:
        condition: service_healthy

volumes:
  pgadmin-data:

networks:
  database-internal:
    external: true
  traefik-public:
    external: true

# Updating pgAdmin labels for correct middleware
