CREATE TABLE IF NOT EXISTS node_workload_desired_states (
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    service_type TEXT NOT NULL,
    desired_state TEXT NOT NULL DEFAULT 'disabled',
    version TEXT,
    runtime_mode TEXT NOT NULL DEFAULT 'container',
    artifact_ref TEXT,
    config JSONB NOT NULL DEFAULT '{}'::JSONB,
    environment JSONB NOT NULL DEFAULT '{}'::JSONB,
    updated_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (cluster_id, node_id, service_type),
    CONSTRAINT node_workload_desired_states_desired_state_check
        CHECK (desired_state IN ('enabled', 'disabled', 'drain')),
    CONSTRAINT node_workload_desired_states_runtime_mode_check
        CHECK (runtime_mode IN ('native', 'container'))
);

CREATE INDEX IF NOT EXISTS idx_node_workload_desired_states_cluster
    ON node_workload_desired_states(cluster_id, service_type, desired_state);

CREATE TABLE IF NOT EXISTS node_workload_status_reports (
    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,
    service_type TEXT NOT NULL,
    reported_state TEXT NOT NULL DEFAULT 'unknown',
    runtime_mode TEXT NOT NULL DEFAULT 'container',
    version TEXT,
    status_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT node_workload_status_reports_reported_state_check
        CHECK (reported_state IN ('unknown', 'starting', 'running', 'degraded', 'stopped', 'failed', 'not_implemented')),
    CONSTRAINT node_workload_status_reports_runtime_mode_check
        CHECK (runtime_mode IN ('native', 'container'))
);

CREATE INDEX IF NOT EXISTS idx_node_workload_status_reports_node_observed
    ON node_workload_status_reports(cluster_id, node_id, observed_at DESC);

CREATE TABLE IF NOT EXISTS node_workload_latest_statuses (
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    service_type TEXT NOT NULL,
    status_report_id UUID REFERENCES node_workload_status_reports(id) ON DELETE SET NULL,
    reported_state TEXT NOT NULL DEFAULT 'unknown',
    runtime_mode TEXT NOT NULL DEFAULT 'container',
    version TEXT,
    status_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (cluster_id, node_id, service_type),
    CONSTRAINT node_workload_latest_statuses_reported_state_check
        CHECK (reported_state IN ('unknown', 'starting', 'running', 'degraded', 'stopped', 'failed', 'not_implemented')),
    CONSTRAINT node_workload_latest_statuses_runtime_mode_check
        CHECK (runtime_mode IN ('native', 'container'))
);
