-- 007 — De-duplicate cluster_nodes by hostname and enforce uniqueness.
--
-- Migration 004 created the table with `CREATE TABLE IF NOT EXISTS` and an
-- inline UNIQUE constraint; on deploys where the table predated 004 the
-- constraint was never applied, which let the same hostname accumulate
-- multiple rows (one per container restart in some setups).
--
-- This migration:
--   1. Deletes older duplicates keeping only the most-recently-seen row
--      per hostname.
--   2. Adds a UNIQUE INDEX on (hostname) which is idempotent and satisfies
--      the ON CONFLICT (hostname) upsert in routes/cluster.js.

DELETE FROM cluster_nodes a
USING cluster_nodes b
WHERE a.hostname = b.hostname
  AND a.last_seen < b.last_seen;

CREATE UNIQUE INDEX IF NOT EXISTS cluster_nodes_hostname_uniq
  ON cluster_nodes (hostname);
