CREATE TABLE IF NOT EXISTS cluster_authorities (
    cluster_id UUID PRIMARY KEY REFERENCES clusters(id) ON DELETE CASCADE,
    authority_state TEXT NOT NULL DEFAULT 'active',
    key_algorithm TEXT NOT NULL DEFAULT 'ed25519',
    public_key TEXT NOT NULL,
    public_key_fingerprint TEXT NOT NULL,
    private_key TEXT NOT NULL,
    created_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    metadata JSONB NOT NULL DEFAULT '{}'::JSONB,
    CONSTRAINT cluster_authorities_state_check
        CHECK (authority_state IN ('active', 'rotating', 'revoked', 'recovery_required')),
    CONSTRAINT cluster_authorities_algorithm_check
        CHECK (key_algorithm = 'ed25519')
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_cluster_authorities_fingerprint
    ON cluster_authorities(public_key_fingerprint);

ALTER TABLE node_join_tokens
    ADD COLUMN IF NOT EXISTS authority_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    ADD COLUMN IF NOT EXISTS authority_signature JSONB NOT NULL DEFAULT '{}'::JSONB;

ALTER TABLE node_join_requests
    ADD COLUMN IF NOT EXISTS approval_payload JSONB NOT NULL DEFAULT '{}'::JSONB,
    ADD COLUMN IF NOT EXISTS approval_signature JSONB NOT NULL DEFAULT '{}'::JSONB;

DROP VIEW IF EXISTS cluster_admin_summaries;

CREATE VIEW cluster_admin_summaries AS
SELECT
    c.id AS cluster_id,
    c.slug,
    c.name,
    c.status,
    c.region,
    COALESCE(cas.authority_state, 'authoritative') AS authority_state,
    COALESCE(cas.mutation_mode, 'normal') AS mutation_mode,
    ca.key_algorithm AS cluster_key_algorithm,
    ca.public_key_fingerprint AS cluster_key_fingerprint,
    COUNT(DISTINCT cm.node_id) AS node_count,
    COUNT(DISTINCT CASE WHEN n.health_status = 'healthy' THEN n.id END) AS healthy_node_count,
    COUNT(DISTINCT CASE WHEN njr.status = 'pending' THEN njr.id END) AS pending_join_count,
    COUNT(DISTINCT nra.id) AS active_role_assignment_count,
    MAX(n.last_seen_at) AS last_node_seen_at
FROM clusters c
LEFT JOIN cluster_authority_states cas ON cas.cluster_id = c.id
LEFT JOIN cluster_authorities ca ON ca.cluster_id = c.id
LEFT JOIN cluster_memberships cm ON cm.cluster_id = c.id
LEFT JOIN nodes n ON n.id = cm.node_id
LEFT JOIN node_join_requests njr ON njr.cluster_id = c.id
LEFT JOIN node_role_assignments nra ON nra.cluster_id = c.id AND nra.status = 'active'
GROUP BY c.id, c.slug, c.name, c.status, c.region, cas.authority_state, cas.mutation_mode, ca.key_algorithm, ca.public_key_fingerprint;
