-- 001_init.sql — initial schema
--
-- agents:    one row per Target agent the controller has ever seen. Updated
--            with each connection + heartbeat. Serves as audit trail — we
--            never delete rows, so an agent disappearing from the network
--            doesn't wipe its history.
-- instances: one row per declared game server. The controller, not the
--            agent, is the source of truth for "instance X exists". Status
--            is updated from InstanceStateUpdate messages streamed up from
--            the agent that owns the instance.

CREATE TABLE agents (
    agent_id   TEXT PRIMARY KEY,
    version    TEXT NOT NULL,
    host_os    TEXT NOT NULL,
    host_arch  TEXT NOT NULL,
    hostname   TEXT NOT NULL,
    first_seen TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    last_seen  TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE TABLE instances (
    instance_id    TEXT PRIMARY KEY,
    agent_id       TEXT NOT NULL,
    module_id      TEXT NOT NULL,
    module_version TEXT,
    run_mode       TEXT NOT NULL DEFAULT 'docker',
    data_path      TEXT,
    config_values  JSONB NOT NULL DEFAULT '{}'::jsonb,
    status         TEXT NOT NULL DEFAULT 'stopped',
    last_exit_code INTEGER,
    detail         TEXT,
    created_at     TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at     TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_instances_agent  ON instances(agent_id);
CREATE INDEX idx_instances_module ON instances(module_id);
CREATE INDEX idx_instances_status ON instances(status);
