-- 010_port_allocation.sql — per-agent port range + per-instance assigned ports
--
-- Why: probing net.Listen for "is this port free?" only catches CURRENTLY
-- bound ports. Two ARK servers, one running, one stopped — the running
-- one's 7777 binding is detected, but the stopped one's intent isn't.
-- Result: a fresh create assigns 7777 to a new server, then the stopped
-- one fails to start because something else now owns its port.
--
-- Fix: persist each instance's assigned host ports in the DB, and let
-- operators set a per-agent port range. Allocation now consults BOTH
-- the persisted assignments AND the live probe — whichever rules out
-- a port first wins.

ALTER TABLE agents
    ADD COLUMN port_range_start INTEGER,
    ADD COLUMN port_range_end   INTEGER;

-- assigned_ports holds the actual host ports the panel allocated for
-- this instance, keyed by manifest port name. Example:
--   {"game": 7777, "raw": 7778, "rcon": 27020}
-- Stays attached even when the instance is stopped — that's the whole
-- point: stopped instances reserve their ports against the next create.
ALTER TABLE instances
    ADD COLUMN assigned_ports JSONB NOT NULL DEFAULT '{}'::jsonb;
