services:
  db:
    image: postgres:17-alpine
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB:-cents}
      POSTGRES_USER: ${POSTGRES_USER:-cents}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - cents_prod_db:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-cents} -d ${POSTGRES_DB:-cents}"]
      interval: 3s
      timeout: 3s
      retries: 20
    networks:
      - app

  api:
    build:
      context: .
      dockerfile: services/api/Dockerfile
    restart: unless-stopped
    environment:
      DATABASE_URL: postgres://${POSTGRES_USER:-cents}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB:-cents}
      PUBLIC_ORIGIN: https://${DOMAIN}
      COOKIE_SECURE: "true"
      APP_TIME_ZONE: ${APP_TIME_ZONE:-Asia/Shanghai}
      EXCHANGE_RATE_API_URL: ${EXCHANGE_RATE_API_URL:-https://api.frankfurter.dev}
      PORT: "3000"
    depends_on:
      db:
        condition: service_healthy
    networks:
      - app

  backup:
    image: cents-backup
    build:
      context: .
      dockerfile_inline: |
        FROM postgres:17-alpine
        RUN apk add --no-cache openssh-client
    restart: unless-stopped
    environment:
      TZ: Asia/Shanghai
      PGHOST: db
      PGDATABASE: ${POSTGRES_DB:-cents}
      PGUSER: ${POSTGRES_USER:-cents}
      PGPASSWORD: ${POSTGRES_PASSWORD}
      BACKUP_SSH_HOST: ${BACKUP_SSH_HOST:-}
      BACKUP_SSH_USER: ${BACKUP_SSH_USER:-backup}
      BACKUP_SSH_PORT: ${BACKUP_SSH_PORT:-22}
      BACKUP_SSH_DIR: ${BACKUP_SSH_DIR:-}
    entrypoint: ["/usr/local/bin/cents-backup"]
    volumes:
      - ./backups:/backups
      - ~/.ssh:/root/.ssh:ro
      - ./deploy/postgres-backup.sh:/usr/local/bin/cents-backup:ro
    depends_on:
      db:
        condition: service_healthy
    healthcheck:
      test: ["CMD", "/usr/local/bin/cents-backup", "health"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 26h
    networks:
      - app

  web:
    build:
      context: .
      dockerfile: apps/web/Dockerfile
      args:
        APP_VARIANT: ${APP_VARIANT:-pro}
    restart: unless-stopped
    depends_on:
      - api
    networks:
      - app

  frpc:
    image: homemade/auto-cert/proxy:latest
    restart: unless-stopped
    environment:
      DOMAIN: ${DOMAIN}
      APP_HOST: web
      APP_PORT: "80"
      APP_PROTOCOL: http
      FRPC_SERVER_HOST: ${FRPC_SERVER_HOST}
      FRPC_SERVER_PORT: ${FRPC_SERVER_PORT}
    volumes:
      - frp_cert_volume:/etc/letsencrypt
    depends_on:
      - web
      - cert
    networks:
      - app
      - frp_prod

  cert:
    image: homemade/auto-cert/cert:latest
    restart: "no"
    command: --domain ${DOMAIN} --test-mode ${TEST_MODE:-false}
    volumes:
      - frp_cert_volume:/etc/letsencrypt
    networks:
      - frp_prod

volumes:
  cents_prod_db:
  frp_cert_volume:

networks:
  app:
    driver: bridge
  frp_prod:
    driver: bridge
