CREATE TABLE IF NOT EXISTS geocode_queue (
  ma_id        BIGINT PRIMARY KEY REFERENCES bands(ma_id) ON DELETE CASCADE,
  query        TEXT NOT NULL,
  country      TEXT,
  status       TEXT NOT NULL DEFAULT 'queued',  -- queued | processing | done | error
  tries        INT  NOT NULL DEFAULT 0,
  next_run_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  last_error   TEXT,
  created_at   TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at   TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_geocode_queue_status_next
  ON geocode_queue (status, next_run_at)
  WHERE status IN ('queued', 'error');

CREATE TABLE IF NOT EXISTS geocode_cache (
  query       TEXT PRIMARY KEY,
  provider    TEXT,
  lat         DOUBLE PRECISION,
  lon         DOUBLE PRECISION,
  geom        GEOGRAPHY(Point, 4326),
  raw         JSONB,
  created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
  updated_at  TIMESTAMPTZ NOT NULL DEFAULT now()
);
