-- IT0 Agent Instances (tenant schema)
-- Tracks deployed OpenClaw containers per tenant/user

CREATE TABLE IF NOT EXISTS agent_instances (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    user_id         UUID NOT NULL,
    name            VARCHAR(100) NOT NULL,               -- User-given name e.g. "我的OpenClaw"
    agent_type      VARCHAR(50) NOT NULL DEFAULT 'openclaw', -- openclaw | future types
    pool_server_id  UUID,                                -- NULL if user-owned server
    server_host     VARCHAR(255) NOT NULL,               -- Actual host used
    ssh_port        INT NOT NULL DEFAULT 22,
    ssh_user        VARCHAR(100) NOT NULL,
    container_name  VARCHAR(150) NOT NULL UNIQUE,        -- docker container name
    host_port       INT NOT NULL,                        -- Mapped port on host (e.g. 20001)
    status          VARCHAR(20) NOT NULL DEFAULT 'deploying', -- deploying|running|stopped|error|removed
    error_message   TEXT,
    openclaw_token  TEXT,                                -- OPENCLAW_GATEWAY_TOKEN (encrypted, base64)
    openclaw_token_iv TEXT,                              -- AES IV (base64)
    config          JSONB NOT NULL DEFAULT '{}',         -- OpenClaw channel configs etc.
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_agent_instances_user ON agent_instances(user_id);
CREATE INDEX IF NOT EXISTS idx_agent_instances_status ON agent_instances(status);
CREATE INDEX IF NOT EXISTS idx_agent_instances_pool_server ON agent_instances(pool_server_id);
