CREATE TABLE IF NOT EXISTS vpn_connection_assignment_status_reports (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    vpn_connection_id UUID NOT NULL REFERENCES vpn_connections(id) ON DELETE CASCADE,
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    observed_status TEXT NOT NULL DEFAULT 'unknown',
    status_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT vpn_connection_assignment_status_membership_fk
        FOREIGN KEY (cluster_id, node_id)
        REFERENCES cluster_memberships(cluster_id, node_id)
        ON DELETE CASCADE,
    CONSTRAINT vpn_connection_assignment_status_check
        CHECK (observed_status IN ('not_started', 'assigned', 'lease_required', 'blocked', 'unknown'))
);

CREATE INDEX IF NOT EXISTS idx_vpn_assignment_status_reports_node
    ON vpn_connection_assignment_status_reports(cluster_id, node_id, observed_at DESC);

CREATE INDEX IF NOT EXISTS idx_vpn_assignment_status_reports_connection
    ON vpn_connection_assignment_status_reports(vpn_connection_id, observed_at DESC);

CREATE TABLE IF NOT EXISTS vpn_connection_assignment_latest_statuses (
    vpn_connection_id UUID NOT NULL REFERENCES vpn_connections(id) ON DELETE CASCADE,
    cluster_id UUID NOT NULL REFERENCES clusters(id) ON DELETE CASCADE,
    node_id UUID NOT NULL REFERENCES nodes(id) ON DELETE CASCADE,
    report_id UUID NOT NULL REFERENCES vpn_connection_assignment_status_reports(id) ON DELETE CASCADE,
    observed_status TEXT NOT NULL,
    status_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    observed_at TIMESTAMPTZ NOT NULL,
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (vpn_connection_id, node_id),
    CONSTRAINT vpn_connection_assignment_latest_membership_fk
        FOREIGN KEY (cluster_id, node_id)
        REFERENCES cluster_memberships(cluster_id, node_id)
        ON DELETE CASCADE,
    CONSTRAINT vpn_connection_assignment_latest_status_check
        CHECK (observed_status IN ('not_started', 'assigned', 'lease_required', 'blocked', 'unknown'))
);

CREATE INDEX IF NOT EXISTS idx_vpn_assignment_latest_node
    ON vpn_connection_assignment_latest_statuses(cluster_id, node_id, updated_at DESC);
