services:
  postgres:
    image: postgres:16-alpine
    restart: always
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-pac}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?postgres password required}
      POSTGRES_DB: ${POSTGRES_DB:-pac}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-pac}"]
      interval: 10s
      retries: 5

  redis:
    image: redis:7-alpine
    restart: always
    command: ["redis-server", "--appendonly", "yes"]
    volumes:
      - redis_data:/data

  # One-shot migrator: applies pending Prisma migrations and exits.
  # Runs before pac-service so the schema is current before any traffic
  # hits the API. Safe to re-run — `migrate deploy` is idempotent.
  pac-migrate:
    build:
      context: .
      dockerfile: apps/pac-service/Dockerfile
      target: prod
    restart: "no"
    depends_on:
      postgres:
        condition: service_healthy
    environment:
      DATABASE_URL: ${DATABASE_URL}
    working_dir: /app/apps/pac-service
    command: ["npx", "prisma", "migrate", "deploy"]

  pac-service:
    build:
      context: .
      dockerfile: apps/pac-service/Dockerfile
      target: prod
    restart: always
    depends_on:
      postgres:
        condition: service_healthy
      redis:
        condition: service_started
      pac-migrate:
        condition: service_completed_successfully
    environment:
      NODE_ENV: production
      PORT: 3001
      DATABASE_URL: ${DATABASE_URL}
      REDIS_URL: ${REDIS_URL}
      JWT_SECRET: ${JWT_SECRET}
      JWT_REFRESH_SECRET: ${JWT_REFRESH_SECRET}
      JWT_EXPIRES_IN: ${JWT_EXPIRES_IN:-2h}
      JWT_REFRESH_EXPIRES_IN: ${JWT_REFRESH_EXPIRES_IN:-7d}
      AI_GATEWAY_URL: ${AI_GATEWAY_URL}
      AI_GATEWAY_API_KEY: ${AI_GATEWAY_API_KEY}
      CORS_ORIGINS: ${CORS_ORIGINS}
      EXCHANGE_CODE_TTL_SECONDS: ${EXCHANGE_CODE_TTL_SECONDS:-60}
    ports:
      - "3001:3001"

  pac-web:
    build:
      context: .
      dockerfile: apps/pac-web/Dockerfile
      target: prod
    restart: always
    depends_on:
      - pac-service
    environment:
      NODE_ENV: production
      NEXT_PUBLIC_API_BASE_URL: ${NEXT_PUBLIC_API_BASE_URL}
    ports:
      - "3000:3000"

volumes:
  postgres_data:
  redis_data:
