services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: chesscubing-web
    depends_on:
      auth:
        condition: service_started
      keycloak:
        condition: service_started
    ports:
      - "8080:80"
    restart: unless-stopped

  auth:
    build:
      context: .
      dockerfile: Dockerfile.auth
    container_name: chesscubing-auth
    environment:
      ASPNETCORE_URLS: http://+:8080
      KEYCLOAK_BASE_URL: http://keycloak:8080/auth
      KEYCLOAK_REALM: chesscubing
      KEYCLOAK_CLIENT_ID: chesscubing-web
      KEYCLOAK_ADMIN_USERNAME: ${KEYCLOAK_ADMIN_USER:-admin}
      KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:-admin}
    depends_on:
      keycloak-init:
        condition: service_completed_successfully
      keycloak:
        condition: service_started
    restart: unless-stopped

  keycloak:
    image: quay.io/keycloak/keycloak:26.1.2
    container_name: chesscubing-keycloak
    command: ["start-dev", "--import-realm"]
    environment:
      KC_DB: postgres
      KC_DB_URL_HOST: postgres
      KC_DB_URL_PORT: 5432
      KC_DB_URL_DATABASE: ${KEYCLOAK_DB_NAME:-keycloak}
      KC_DB_USERNAME: ${KEYCLOAK_DB_USER:-keycloak}
      KC_DB_PASSWORD: ${KEYCLOAK_DB_PASSWORD:-keycloak}
      KC_BOOTSTRAP_ADMIN_USERNAME: ${KEYCLOAK_ADMIN_USER:-admin}
      KC_BOOTSTRAP_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:-admin}
      KC_PROXY_HEADERS: xforwarded
      KC_HOSTNAME: http://localhost:8080/auth
      KC_HTTP_RELATIVE_PATH: /auth
      KC_HOSTNAME_STRICT: "false"
    volumes:
      - ./keycloak/realm:/opt/keycloak/data/import:ro
    depends_on:
      postgres:
        condition: service_healthy
    restart: unless-stopped

  keycloak-init:
    image: quay.io/keycloak/keycloak:26.1.2
    container_name: chesscubing-keycloak-init
    entrypoint: ["/bin/sh", "/opt/keycloak/data/scripts/init-config.sh"]
    environment:
      KEYCLOAK_URL: http://keycloak:8080/auth
      KEYCLOAK_REALM: chesscubing
      KEYCLOAK_CLIENT_ID: chesscubing-web
      KEYCLOAK_ADMIN_USERNAME: ${KEYCLOAK_ADMIN_USER:-admin}
      KEYCLOAK_ADMIN_PASSWORD: ${KEYCLOAK_ADMIN_PASSWORD:-admin}
    volumes:
      - ./keycloak/scripts:/opt/keycloak/data/scripts:ro
    depends_on:
      keycloak:
        condition: service_started
    restart: "no"

  postgres:
    image: postgres:16-alpine
    container_name: chesscubing-keycloak-db
    environment:
      POSTGRES_DB: ${KEYCLOAK_DB_NAME:-keycloak}
      POSTGRES_USER: ${KEYCLOAK_DB_USER:-keycloak}
      POSTGRES_PASSWORD: ${KEYCLOAK_DB_PASSWORD:-keycloak}
    volumes:
      - keycloak-postgres:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${KEYCLOAK_DB_USER:-keycloak} -d ${KEYCLOAK_DB_NAME:-keycloak}"]
      interval: 10s
      timeout: 5s
      retries: 5
    restart: unless-stopped

volumes:
  keycloak-postgres:
