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'
         AND n.last_seen_at >= NOW() - '1 minute'::interval 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;
