CREATE TABLE IF NOT EXISTS fabric_service_channel_leases (
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    channel_id UUID NOT NULL,
    token_hash TEXT NOT NULL,
    resource_id TEXT NOT NULL DEFAULT '',
    service_class TEXT NOT NULL,
    selected_entry_node_id UUID NULL REFERENCES nodes(id) ON DELETE SET NULL,
    expires_at TIMESTAMPTZ NOT NULL,
    lease JSONB NOT NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (cluster_id, channel_id)
);

CREATE INDEX IF NOT EXISTS fabric_service_channel_leases_cluster_expires_idx
    ON fabric_service_channel_leases(cluster_id, expires_at);

CREATE INDEX IF NOT EXISTS fabric_service_channel_leases_entry_idx
    ON fabric_service_channel_leases(cluster_id, selected_entry_node_id, expires_at);
