-- Ensure approved communities inherit instance defaults
-- Applies instance default visibility and initializes community_settings with instance defaults

CREATE OR REPLACE FUNCTION approve_community(
    p_pending_id UUID,
    p_reviewer_id UUID
) RETURNS UUID AS $$
DECLARE
    v_pending pending_communities%ROWTYPE;
    v_community_id UUID;
    v_default_visibility VARCHAR(20);
    v_default_plugin_policy VARCHAR(20);
    v_default_moderation_mode VARCHAR(20);
BEGIN
    -- Get pending community
    SELECT * INTO v_pending FROM pending_communities WHERE id = p_pending_id AND status = 'pending';
    IF NOT FOUND THEN
        RAISE EXCEPTION 'Pending community not found or already processed';
    END IF;

    SELECT default_community_visibility,
           default_plugin_policy,
           default_moderation_mode
    INTO v_default_visibility,
         v_default_plugin_policy,
         v_default_moderation_mode
    FROM instance_settings
    LIMIT 1;

    -- Create the community
    INSERT INTO communities (name, slug, description, settings, created_by, is_active)
    VALUES (
        v_pending.name,
        v_pending.slug,
        v_pending.description,
        jsonb_build_object('visibility', v_default_visibility),
        v_pending.requested_by,
        true
    )
    RETURNING id INTO v_community_id;

    -- Add requester as admin
    INSERT INTO community_members (community_id, user_id, role)
    VALUES (v_community_id, v_pending.requested_by, 'admin');

    INSERT INTO community_settings (community_id, moderation_mode, plugin_policy)
    VALUES (v_community_id, v_default_moderation_mode, v_default_plugin_policy)
    ON CONFLICT DO NOTHING;

    -- Mark as approved
    UPDATE pending_communities
    SET status = 'approved', reviewed_by = p_reviewer_id, reviewed_at = NOW()
    WHERE id = p_pending_id;

    RETURN v_community_id;
END;
$$ LANGUAGE plpgsql;
