# Exercise 3 — Health Checks and Real Readiness (hardest)
#
# Fix the race condition from theory section 4: `api` currently starts
# before `db` is actually ready to accept connections, because plain
# `depends_on` only waits for the container to START, not for Postgres
# to finish initializing.
#
# STEP 1: add a `healthcheck` to `db` that runs `pg_isready -U appuser`
#         via CMD-SHELL, checking every 5s, timing out after 3s, with 5
#         retries before being marked unhealthy.
# STEP 2: change `api`'s `depends_on` from the plain array form to the
#         expanded object form, requiring `db` to report
#         `condition: service_healthy` before `api`'s container is even
#         created.
# STEP 3: add a healthcheck to `api` ITSELF, hitting its own HTTP health
#         endpoint at http://localhost:3000/health using `curl -f` (the
#         -f flag makes curl exit non-zero on an HTTP error status, which
#         is what a healthcheck's exit code needs to reflect readiness
#         correctly).
#
# No YAML interpreter self-check — verify against the CHECKLIST below.

services:
  api:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      db:
        # TODO 1: require db to be reported healthy, not just started
        condition: TODO
    # TODO 2: api's own healthcheck hitting its /health endpoint with curl -f
    healthcheck:
      test: TODO
      interval: 5s
      timeout: 3s
      retries: 5

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: appuser
      POSTGRES_PASSWORD: devpass123
    # TODO 3: db's healthcheck using pg_isready -U appuser
    healthcheck:
      test: TODO
      interval: 5s
      timeout: 3s
      retries: 5

# ---------------------------------------------------------------------------
# CHECKLIST:
# [ ] `db.healthcheck.test` is `["CMD-SHELL", "pg_isready -U appuser"]`
#     (or equivalent CMD-SHELL form) — exercises the actual Postgres
#     readiness probe, not a fake "always pass" check.
# [ ] `api.depends_on.db.condition` is exactly `service_healthy`, using
#     the EXPANDED object form, not the plain array form from Exercise 1.
# [ ] `api.healthcheck.test` uses `curl -f` (or equivalent) against
#     `/health`, so a non-2xx response makes the check fail — not just
#     "the port accepts a TCP connection."
# [ ] On `docker compose up`, `api`'s container is NOT created until
#     `docker compose ps` (checked mid-startup) shows `db` as `healthy`,
#     not merely `running` — this is the behavioral difference this
#     exercise is testing for versus Exercise 1's plain depends_on.
# [ ] Explain in a one-line comment at the bottom of this file: why would
#     `condition: service_started` (instead of `service_healthy`) defeat
#     the entire purpose of adding a healthcheck to `db` in the first
#     place?
# ---------------------------------------------------------------------------
