CREATE TABLE IF NOT EXISTS fabric_testing_flags (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    scope_type TEXT NOT NULL,
    scope_id UUID,
    cluster_id UUID REFERENCES clusters(id) ON DELETE CASCADE,
    enabled BOOLEAN NOT NULL DEFAULT FALSE,
    telemetry_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    synthetic_links_enabled BOOLEAN NOT NULL DEFAULT FALSE,
    history_retention_hours INTEGER NOT NULL DEFAULT 24,
    metadata JSONB NOT NULL DEFAULT '{}'::JSONB,
    updated_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT fabric_testing_flags_scope_check
        CHECK (scope_type IN ('platform', 'organization', 'node')),
    CONSTRAINT fabric_testing_flags_retention_check
        CHECK (history_retention_hours BETWEEN 1 AND 720)
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_fabric_testing_flags_unique_scope
    ON fabric_testing_flags (
        scope_type,
        COALESCE(scope_id, '00000000-0000-0000-0000-000000000000'::uuid),
        COALESCE(cluster_id, '00000000-0000-0000-0000-000000000000'::uuid)
    );

CREATE TABLE IF NOT EXISTS node_telemetry_observations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    cpu_percent DOUBLE PRECISION,
    memory_used_bytes BIGINT,
    memory_total_bytes BIGINT,
    disk_used_bytes BIGINT,
    disk_total_bytes BIGINT,
    network_rx_bytes BIGINT,
    network_tx_bytes BIGINT,
    process_count INTEGER,
    payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);

CREATE INDEX IF NOT EXISTS idx_node_telemetry_cluster_node_observed
    ON node_telemetry_observations(cluster_id, node_id, observed_at DESC);
