CREATE TABLE IF NOT EXISTS gateway_access_rules ( id uuid PRIMARY KEY DEFAULT gen_random_uuid(), subject_type text NOT NULL CHECK (subject_type IN ('user_group', 'tenant', 'user', 'api_key')), subject_id uuid NOT NULL, resource_type text NOT NULL CHECK (resource_type IN ('platform', 'platform_model', 'base_model')), resource_id uuid NOT NULL, effect text NOT NULL CHECK (effect IN ('allow', 'deny')), priority integer NOT NULL DEFAULT 100, min_permission_level integer NOT NULL DEFAULT 0, conditions jsonb NOT NULL DEFAULT '{}'::jsonb, metadata jsonb NOT NULL DEFAULT '{}'::jsonb, status text NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(), UNIQUE (subject_type, subject_id, resource_type, resource_id, effect) ); CREATE INDEX IF NOT EXISTS idx_gateway_access_rules_subject ON gateway_access_rules(subject_type, subject_id, status); CREATE INDEX IF NOT EXISTS idx_gateway_access_rules_resource ON gateway_access_rules(resource_type, resource_id, status); CREATE INDEX IF NOT EXISTS idx_gateway_access_rules_effect ON gateway_access_rules(effect, status, priority);